In Python, how do you convert seconds since epoch to a `datetime` object?

Adam Matan picture Adam Matan · Sep 12, 2010 · Viewed 270.7k times · Source

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?

Answer

SilentGhost picture SilentGhost · Sep 12, 2010

datetime.datetime.fromtimestamp will do, if you know the time zone, you could produce the same output as with time.gmtime

>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)

or

>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)