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) a
You are correct that this behavior is related to daylight savings time. The easiest way to avoid this is to ensure you use a time zone without daylight savings, UTC makes the most sense here.
datetime.datetime.utcfromtimestamp() and calendar.timegm() deal with UTC times, and are exact inverses.
import calendar, datetime
# Convert a unix time u to a datetime object d, and vice versa
def dt(u): return datetime.datetime.utcfromtimestamp(u)
def ut(d): return calendar.timegm(d.timetuple())
Here is a bit of explanation behind why datetime.datetime.fromtimestamp() has an issue with daylight savings time, from the docs:
Return the local date and time corresponding to the POSIX timestamp, such as is returned by
time.time()
. If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.
The important part here is that you get a naive datetime.datetime
object, which means there is no timezone (or daylight savings) information as a part of the object. This means that multiple distinct timestamps can map to the same datetime.datetime
object when using fromtimestamp()
, if you happen to pick times that fall during the daylight savings time roll back:
>>> datetime.datetime.fromtimestamp(1004260000)
datetime.datetime(2001, 10, 28, 1, 6, 40)
>>> datetime.datetime.fromtimestamp(1004256400)
datetime.datetime(2001, 10, 28, 1, 6, 40)