I have dt = datetime(2013,9,1,11)
, and I would like to get a Unix timestamp of this datetime object.
When I do (dt - datetime(1970,1,1)).total_seconds()
I got the timestamp 1378033200
.
When converting it back using datetime.fromtimestamp
I got datetime.datetime(2013, 9, 1, 6, 0)
.
The hour doesn’t match. What did I miss here?
Advertisement
Answer
What you missed here is timezones.
Presumably you’ve five hours off UTC, so 2013-09-01T11:00:00 local and 2013-09-01T06:00:00Z are the same time.
You need to read the top of the datetime
docs, which explain about timezones and “naive” and “aware” objects.
If your original naive datetime was UTC, the way to recover it is to use utcfromtimestamp
instead of fromtimestamp
.
On the other hand, if your original naive datetime was local, you shouldn’t have subtracted a UTC timestamp from it in the first place; use datetime.fromtimestamp(0)
instead.
Or, if you had an aware datetime object, you need to either use a local (aware) epoch on both sides, or explicitly convert to and from UTC.
If you have, or can upgrade to, Python 3.3 or later, you can avoid all of these problems by just using the timestamp
method instead of trying to figure out how to do it yourself. And even if you don’t, you may want to consider borrowing its source code.
(And if you can wait for Python 3.4, it looks like PEP 341 is likely to make it into the final release, which means all of the stuff J.F. Sebastian and I were talking about in the comments should be doable with just the stdlib, and working the same way on both Unix and Windows.)