为什么 datetime.now(datetime.timezone.utc) 和 datetime.datetime.utcnow() 之间的区别

Why the difference between datetime.now(datetime.timezone.utc) and datetime.datetime.utcnow()

如果你调用 datetime.datetime.now(datetime.timezone.utc) 你会得到类似 datetime.datetime(2021, 9, 8, 1, 33, 19, 684253, tzinfo=datetime.timezone.utc).

的结果

如果你调用 datetime.datetime.utcnow(),你会得到类似 datetime.datetime(2021, 9, 8, 1, 33, 20, 283212) 的结果。

结果似乎相同,但实际上并非如此,因为 时间戳 会有所不同。例如。调用 datetime.datetime.now(datetime.timezone.utc).timestamp() - datetime.datetime.utcnow().timestamp() returns(对我来说):-18000.000012159348.

这是为什么?

import datetime

print()
print(datetime.datetime.now(datetime.timezone.utc))
print(datetime.datetime.utcnow())

print()
print(datetime.datetime.now(datetime.timezone.utc).timestamp())
print(datetime.datetime.utcnow().timestamp())
print(datetime.datetime.now(datetime.timezone.utc).timestamp() - datetime.datetime.utcnow().timestamp())

utcnow 创建一个简单的 datetime 实例,因为在 Python 中引入时没有 UTC 时区对象。来自 timestamp() 的文档:

Naive datetime instances are assumed to represent local time and this method relies on the platform C mktime() function to perform the conversion.

此行为已记录在案。发生这种情况是因为 utcnow() returns 天真的日期时间。

datetime.utcnow()

Return the current UTC date and time, with tzinfo None.

This is like now(), but returns the current UTC date and time, as a naive datetime object. An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc).

这就是为什么文档还说 datetime.now()

This function is preferred over today() and utcnow().