gpt4 book ai didi

python - addheaders if-modified-since 现在加上 60 秒

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

我是 python 的新手,正在尝试做一些看似微不足道的事情:我想将 if-not-modified header 添加到传递时间的 http 请求中,现在减去 60 秒。我在 now() - 60 秒部分遇到了很多困难。

我看过这个How do I convert local time to UTC in Python? , 这个How can I convert a datetime object to milliseconds since epoch (unix time) in Python? ,以及许多其他问题,但必须有比这种方法更直接的方法:

time.strftime("%Y-%m-%d %H:%M:%S", 
time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00",
"%Y-%m-%d %H:%M:%S"))))

获取正确的时间并将其作为参数传递给 addheaders。

到目前为止,这是我的代码:

interval = 60 #changes other places 
timestamp = datetime.datetime.now() - datetime.timedelta(seconds=interval)

opener.addheaders("if-modified-since", time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.mktime(time.strptime(timestamp, "%Y-%m-%d %H:%M:%S")))))

它会抛出一个 TypeError: expected string or buffer 但总而言之,为了得到像 now() + 60 秒这样简单的东西,经过这么多的思考似乎是完全疯狂的UTC 字符串。有更多 python ninja-foo 的人可以帮我看看我的方法有什么错误吗?

最佳答案

datetime 有一个方法 utcnow它以 UTC 而非本地时间返回当前时间,因此您可以将代码缩短为:

from datetime import datetime, timedelta
timestamp = datetime.utcnow() + timedelta(seconds=60)
opener.addheaders("if-modified-since", timestamp.strftime('%a, %d %b %Y %H:%M:%S GMT'))

关于python - addheaders if-modified-since 现在加上 60 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17930157/

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