Search code examples
pythondatedatetimeutciso8601

Timestamp to UTC ISO 8601 date


This

import datetime
datetime.datetime.fromtimestamp(1501545600).isoformat()

should output 2017-08-01T00:00:00Z or 2017-08-01T00:00:00 but I get

2017-08-01T02:00:00

instead, probably because of local timezone.

How to make .isoformat() output an UTC time instead, i.e. 2017-08-01T00:00:00?

If possible I'd like to use only datetime, and no other third party library like arrow or dateutils.


Solution

  • Use utcfromtimestamp() rather than fromtimestamp(). From the docs:

    Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None.

    With no tzinfo specified in fromtimestamp():

    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.

    Which doesn't seem to be what you want.