I'm trying to write a pair of functions, dt
and ut
, that convert back and forth between normal unix time (seconds since 1970-01-01 00:00:00 UTC) and a Python datetime object.
If dt
and ut
were proper inverses then this code would print the same timestamp twice:
import time, datetime
# Convert a unix time u to a datetime object d, and vice versa
def dt(u): return datetime.datetime.fromtimestamp(u)
def ut(d): return time.mktime(d.timetuple())
u = 1004260000
print u, "-->", ut(dt(u))
Alas, the second timestamp is 3600 seconds (an hour) less than the first.
I think this only happens for very particular unixtimes, maybe during that hour that daylight savings time skips over.
But is there a way to write dt
and ut
so they're true inverses of each other?
Related question: Making matplotlib's date2num and num2date perfect inverses