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

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


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)


Seconds since epoch to datetime to strftime:

>>> ts_epoch = 1362301382>>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S')>>> ts'2013-03-03 01:03:02'


From the docs, the recommended way of getting a timezone aware datetime object from seconds since epoch is:

Python 3:

from datetime import datetime, timezonedatetime.fromtimestamp(timestamp, timezone.utc)

Python 2, using pytz:

from datetime import datetimeimport pytzdatetime.fromtimestamp(timestamp, pytz.utc)