Convert a unixtime to a datetime object and back again (pair of time conversion functions that are inverses)

你离开我真会死。 提交于 2019-11-28 21:11:38

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!