Reputation: 18745
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?
Upvotes: 7
Views: 10805
Reputation: 1545
It is not a good idea to use datetime.datetime.utcfromtimestamp()
. It returns a naive datetime object (without time zone information) which would be interpreted by many functions as datetime
in your local time zone! It is much better to use time zone aware objects.
The following code returns time zone aware datetime
in the UTC time zone.
>>> import datetime
>>> datetime.datetime.fromtimestamp(1566720000, datetime.timezone.utc)
datetime.datetime(2019, 8, 25, 8, 0, tzinfo=datetime.timezone.utc)
Upvotes: 4
Reputation: 43870
Looks like you want utcfromtimestamp
>>> datetime.datetime.utcfromtimestamp(1566720000)
datetime.datetime(2019, 8, 25, 8, 0)
Keep in mind this still returns a naive datetime object
Upvotes: 4
Reputation: 459
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)
Upvotes: 6