344

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?

Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177
Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • 4
    for the opposite operation go here: [convert-a-datetime-object-to-seconds](https://stackoverflow.com/questions/7852855/in-python-how-do-you-convert-a-datetime-object-to-seconds) – Trevor Boyd Smith Dec 06 '18 at 19:02

5 Answers5

541

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)
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • 54
    bizarrely, `datetime.utcfromtimestamp` creates a naive timestamp. I had to `import pytz` and use `datetime.fromtimestamp(1423524051, pytz.utc)` to create an aware datetime. – Matt Feb 09 '15 at 23:21
  • 23
    as a follow-on to the above, with Python >= 3.2 you don't have to import the `pytz` library if you only want the UTC timestamp - you only need to `from datetime import datetime, timezone` and then call it as follows: `datetime.fromtimestamp(1423524051, timezone.utc)`. It has saved the extra library many times when I only need the UTC timezone from `pytz`. – phouse512 Jan 10 '18 at 17:28
61

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'
Seganku
  • 711
  • 5
  • 3
  • It should be datetime.fromtimestamp(1579366345).strftime('%Y-%m-%d %H:%M:%S') – vml19 Apr 05 '20 at 03:37
  • 1
    @vml19, it depends on whether `datetime` was imported from `datetime` or not (`import datetime` vs. `from datetime import datetime`). – Alex Peters May 27 '21 at 11:21
50

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

Python 3:

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

Python 2, using pytz:

from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)
Jens
  • 8,423
  • 9
  • 58
  • 78
Meistro
  • 3,664
  • 2
  • 28
  • 33
  • 1
    A link to the documentation in your subtitles ("Python 3", "Python 2") would be useful - and I also recommend changing their order. – Adam Matan Jan 08 '16 at 11:45
  • Updated. Leaving the order the same, since that matches the Python docs. – Meistro Jan 08 '16 at 16:42
  • you don't need `pytz` just to get `utc` tzinfo object. [It is easy to create it yourself](http://stackoverflow.com/a/2331635/4279) – jfs Jan 09 '16 at 07:26
10

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:

"This may raise ValueError, if the timestamp is out of the range of values supported by the platform C gmtime() function. It’s common for this to be restricted to years in 1970 through 2038"

See also Issue1646728

cbare
  • 12,060
  • 8
  • 56
  • 63
5

For those that want it ISO 8601 compliant, since the other solutions do not have the T separator nor the time offset (except Meistro's answer):

from datetime import datetime, timezone
result = datetime.fromtimestamp(1463288494, timezone.utc).isoformat('T', 'microseconds')
print(result) # 2016-05-15T05:01:34.000000+00:00

Note, I use fromtimestamp because if I used utcfromtimestamp I would need to chain on .astimezone(...) anyway to get the offset.

If you don't want to go all the way to microseconds you can choose a different unit with the isoformat() method.