pythondatetimegmt

datetime.fromtimestamp() - returns my local timezone instead of GMT


I have a problem converting timestamp to GMT. As far as I know, the timestamp is allways in GMT time so I expect datetime.fromtimestamp returning GMT or timezone-aware datetime but it returns my local (Bratislava/Prague) datetime.

import datetime
datetime.datetime.fromtimestamp(1566720000)
datetime.datetime(2019, 8, 25, 10, 0)

But according to Epoch Converter it is

GMT: Sunday, August 25, 2019 8:00:00 AM

EDIT: datetime.datetime.fromtimestamp(1566720000).tzinfo returns nothing so it is not tz aware.

Do you know where is the problem?


Solution

  • fromtimestamp() returns the local date and time. If it needs to be tz-aware, the parameter tz must be specified:

    https://docs.python.org/3/library/datetime.html#datetime.datetime.fromtimestamp

    Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). 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.

    If you need the a datetime object in UTC, use utcfromtimestamp instead:

    datetime.utcfromtimestamp(timestamp)