2

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

我看过这个如何在 Python 中将本地时间转换为 UTC?,这如何在 Python 中将日期时间对象转换为自纪元(unix 时间)以来的毫秒数?,以及许多其他问题,但必须有比这种方法更直接的方法:

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"))))

获取正确的时间并将其作为 arg 传递给 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 seconds 这样简单的 UTC 字符串,这似乎是一种完全的精神错乱。有更多 python ninja-foo 的人可以帮我看看我的方式的错误吗?

4

1 回答 1

3

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'))
于 2013-07-29T19:33:19.640 回答