繁体   English   中英

比较datetime.now()与python 2.7的utc时间戳

[英]compare datetime.now() with utc timestamp with python 2.7

我有一个时间戳,例如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() ,以确保正确处理时区:-)。

正如@mgilson指出的那样,您的输入可能是“毫秒”,而不是“自纪元以来的秒数”。

使用time.time()代替datetime.now()

import time

if time.time() > (timestamp_in_millis * 1e-3):
    print("expired")

如果需要datetime使用datetime.utcnow()代替datetime.now() 不要比较.now()返回本地时间与一个天真的DateTime对象utcfromtimestamp()也返回UTC时间,一个天真的DateTime对象(这是比较喜欢摄氏和华氏直接:你应该转换成同一单位第一)。

from datetime import datetime

now = datetime.utcnow()
then = datetime.utcfromtimestamp(timestamp_in_millis * 1e-3)
if now > then:
    print("expired")

查找日期时间之间是否经过24小时-Python中查看更多详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM