gpt4 book ai didi

python - 为什么 datetime.now(datetime.timezone.utc) 和 datetime.datetime.utcnow() 之间存在差异

转载 作者:行者123 更新时间:2023-12-03 08:16:56 29 4
gpt4 key购买 nike

如果您调用 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() 返回(对我来说):-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.utcnow()

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

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

这就是为什么文档还提到了 datetime.now()

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

关于python - 为什么 datetime.now(datetime.timezone.utc) 和 datetime.datetime.utcnow() 之间存在差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69096039/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com