The time
module can be initialized using seconds since epoch:
>>> import time
>>> t1=time.gmtime(1284286794)
>>> t1
time.struct_time(tm_year=2010, tm_mon=9, tm_mday=12, tm_hour=10, tm_min=19,
tm_sec=54, tm_wday=6, tm_yday=255, tm_isdst=0)
Is there an elegant way to initialize a datetime.datetime
object in the same way?
From the docs, the recommended way of getting a timezone aware datetime object from seconds since epoch is:
Python 3:
Python 2, using
pytz
:Seconds since epoch to
datetime
tostrftime
:datetime.datetime.fromtimestamp
will do, if you know the time zone, you could produce the same output as withtime.gmtime
or
Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:
See also Issue1646728