start

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 print(timezone(timezone(hours=2)).timestamp()) ==== output 1626687759.9081082 1626658959.908108 1626687759.908108 1626687759.908108

I found that only utcnow() was different in the output timestamp. If I compared the time difference, I could find that the difference was exactly 8 hours, and the time zone where my computer was located was East 8.

why

As the utcNow () documentation makes clear, it returns naive time. Naive DateTime instances are considered to represent the local time, so its timestamp will be exactly the time zone in which the computer is located compared to using NOW (NONE).

There is a historical reason for this quirky handling. Datetime. timezone was designed as a new feature in version 3.2 during the transition from Python 2 to Python 3, so it is much clearer to mark the timezone of the date. The old interface, utcnow(), retains its old handling.

The new time zone model is handled in a way that is incompatible 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())

conclusion

With all that said, utcnow() is probably a common pitfall. I recommend no longer using utcnow() and utcfromtimestamp().