2

Get started

Execute the following code:

import time
from datetime import datetime, timezone, timedelta

print(time.time())
print(datetime.utcnow().timestamp())
print(datetime.now(timezone.utc).timestamp())
print(datetime.now(timezone(timedelta(hours=2))).timestamp())

==== output ====
1626687759.9081082
1626658959.908108
1626687759.908108
1626687759.908108

It is found that only utcnow() in the output timestamp is different. If you compare the time difference, you can find that the difference is exactly 8 hours, and the time zone of my computer is exactly the Dongba District.

the reason

As utcnow() document indicates, it returns naive time , Naive datetime instance is considered to represent local time, so its timestamp will be now(None) in the time zone of the computer.

There are historical reasons for this weird processing method. In the transition phase from Python 2 to Python 3, datetime.timezone was designed as a new feature in version 3.2, so it has a clearer and clearer mark The time zone in which the date is located. The old interface utcnow() retains the original processing method.

The new time zone model has compatibility issues with Python 2:

==== Python 2 ====
>>> from datetime import datetime
>>> from dateutil import tz
>>> datetime(2021, 5, 1).astimezone(tz.UTC)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime

==== Python 3 ====
>>> from datetime import datetime
>>> from dateutil import tz
>>> datetime(2021, 5, 1).astimezone(tz.UTC)
datetime.datetime(2021, 5, 1, 4, 0, tzinfo=tzutc())

to sum up

In summary, utcnow() may be a common trap. I suggest not to use utcnow() and utcfromtimestamp() .


陆安
3.2k 声望239 粉丝

宝可梦情怀粉;刀塔手残党;浴室麦霸王。