Convert a unixtime to a datetime object and back again (pair of time conversion functions that are inverses)
Convert a unixtime to a datetime object and back again (pair of time conversion functions that are inverses)
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping
--
Chapters
00:00 Question
01:16 Accepted answer (Score 41)
03:00 Thank you
--
Full question
https://stackoverflow.com/questions/1326...
Question links:
[Making matplotlib's date2num and num2date perfect inverses]: https://stackoverflow.com/questions/1325...
Accepted answer links:
[datetime.datetime.utcfromtimestamp()]: http://docs.python.org/2/library/datetim...
[calendar.timegm()]: http://docs.python.org/2/library/calenda...
[datetime.datetime.fromtimestamp()]: http://docs.python.org/2/library/datetim...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #date #datetime #time #dst
#avk47
ACCEPTED ANSWER
Score 41
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)