Please use datetime.utcnow() with caution

weapon
中文

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() .

阅读 644

编程进阶之路
清茗浮碗,文书闲展,与君俯首三食对案,两相顾颜欢。

闲来笑浮生悬笔一卷入毫端,朱绂临身可与言者不过二三,一衣洒扫风雨气愈扬,争个地平天成云清月朗。

3.2k 声望
230 粉丝
0 条评论
你知道吗?

闲来笑浮生悬笔一卷入毫端,朱绂临身可与言者不过二三,一衣洒扫风雨气愈扬,争个地平天成云清月朗。

3.2k 声望
230 粉丝
宣传栏