python - python中的时间和日期时间差异触发错误

标签 python django datetime

我正在使用 Django 应用程序 Pyroven 并对其功能进行一些重大修改。作为其中的一部分,我已经开始为其编写一个测试框架,因为目前它没有单元测试。在后台,它使用 University of Cambridge Raven service 进行身份验证,并为 Django 提供身份验证后端以利用此服务。

我遇到的问题是测试 Raven 的 WLS-Response token 。这形成了一个由 ! 分隔的值组成的字符串,其中包括格式如下的时间字段:

%Y%m%dT%H%M%SZ

在我的测试代码中,我将其创建为:

raven_issue = datetime.now().strftime('%Y%m%dT%H%M%SZ')

然后将其返回到测试 URL 以供 View 处理。问题在于验证这个时间对于验证响应来说并不算太远。验证这一点的代码使用:

def parse_time(t):
    """Converts a time of the form '20110729T123456Z' to a number of seconds
    since the epoch.
    @exception ValueError if the time is not a valid Raven time"""
    time_struct = time.strptime(t, "%Y%m%dT%H%M%SZ")
    return calendar.timegm(time_struct)

现在,当从 datetime.now() 构造函数传递上面的字符串时,对该解析值的验证失败:

# Check that the issue time is not in the future or too far in the past:
if self.issue > time.time() + PYROVEN_MAX_CLOCK_SKEW:
    raise InvalidResponseError("The timestamp on the response is in the future")
if self.issue < time.time() - PYROVEN_MAX_CLOCK_SKEW - PYROVEN_TIMEOUT: 
    raise InvalidResponseError("The response has timed out")

此代码在我的测试中失败,声称响应已超时。 PYROVEN_MAX_CLOCK_SKEWPYROVEN_TIMEOUT 的值分别为 2 秒和 10 秒。

这引出了一个问题,在处理时间方面是否存在一些我不明白的变化?如果我输入一个 datetime.now() 生成的值,其中 datetime.timedelta 为 future 2 小时,将其转换为字符串并将其传递给验证,尽管时间戳是在未来,但它不会失败。为什么会这样,正如代码的逻辑阅读所暗示的那样?

最佳答案

您对本地时间(由 datetime.now() 返回)和 GMT(由 calendar.timegm() 解析)感到困惑:

>>> t = datetime.now().strftime('%Y%m%dT%H%M%SZ')
>>> t
'20120910T232358Z'
>>> calendar.timegm(time.strptime(t, "%Y%m%dT%H%M%SZ"))
1347319438
>>> time.mktime(time.localtime())
1347312258.0
>>> time.mktime(time.strptime(t, "%Y%m%dT%H%M%SZ"))
1347312238.0

结论:使用 time.mktime 而不是 calendar.timegm 将值转换为时间戳。

关于python - python中的时间和日期时间差异触发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12359507/

相关文章:

PHP 持续时间下拉列表

python - 解释 HIDAPI python 输出

Python sh 模块 - 如何显示构造的命令字符串

python - Pynput 键盘记录器仅返回 Shift、Command、空格和 Capslock 键

python - 如何将cookie添加到tornado httpclient

python - 在 Python 中以二进制格式写入和读取日期时间

Django 现在在 Heroku 中与 ASGI + WSGI 合作

django - 使用 Django 的本地开发服务器时,本地站点未在 VirtualBox 中显示?

Django + Ec2 -> 显示 "runserver"控制台输出

python - pandas 重新采样改变索引的数值