SoFunction
Updated on 2024-12-20

Python Usage Problem Analysis

set in motion

Execute the following code:

import time
from datetime import datetime, timezone, timedelta
print(())
print(().timestamp())
print(().timestamp())
print((timezone(timedelta(hours=2))).timestamp())
==== output ====
1626687759.9081082
1626658959.908108
1626687759.908108
1626687759.908108

It was found that the only timestamps in the output wereutcnow() It's not the same, if you compare the time difference you can see that the difference is exactly 8 hours, and the time zone of my computer is exactly 8 hours east.

rationale

precisely asutcnow() (computer) file As indicated, it returns thenaive time The ,Naive datetime instance is assumed to represent local time, so its timestamps will be more accurate than if you use thenow(None) The difference in time is exactly the time zone in which that computer is located.

There's a historical reason for this weird treatment; during the transition from Python 2 to Python 3, the Designed as a new feature in version 3.2, so that there is a clearer and more explicit labeling of the time zone where the date is located. Old Interfaceutcnow() The original treatment was retained.

There is a compatibility issue with Python 2 in the way the new time zone model is handled:

==== Python 2 ====
>>> from datetime import datetime
>>> from dateutil import tz
>>> datetime(2021, 5, 1).astimezone()
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()
(2021, 5, 1, 4, 0, tzinfo=tzutc())

summarize

In summary.utcnow() Could be a common pitfall.

I would recommend not using it again.utcnow() respond in singingutcfromtimestamp() 。

Above is the detailed content of python using () problem analysis, more information about python () please pay attention to my other related articles!