gpt4 book ai didi

python - 将 datetime.now() 与 python 2.7 的 utc 时间戳进行比较

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:56 25 4
gpt4 key购买 nike

我有一个时间戳,例如 1474398821633L,我认为它是 utc 格式的。我想将它与 datetime.datetime.now() 进行比较以验证它是否已过期。

我正在使用 python 2.7

from datetime import datetime

timestamp = 1474398821633L
now = datetime.now()

if datetime.utcfromtimestamp(timestamp) < now:
print "timestamp expired"

然而,当我尝试从时间戳创建日期时间对象时遇到此错误:ValueError: timestamp out of range for platform localtime()/gmtime() function

我能做什么?

最佳答案

看起来您的时间戳以毫秒为单位。 Python 使用以秒为单位的时间戳:

>>> datetime.datetime.utcfromtimestamp(1474398821.633)
datetime.datetime(2016, 9, 20, 19, 13, 41, 633000)

换句话说,您可能需要将时间戳除以 1000。 才能使其处于正确的范围内。

此外,您可能希望比较 datetime.utcnow() 而不是 datetime.now() 以确保您正确处理时区:- ).

关于python - 将 datetime.now() 与 python 2.7 的 utc 时间戳进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39602188/

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