[英]Converting http request time to unix timestamp in Python
Folks, How would I convert the following string to a unix epoch timestamp? 伙计们,我如何将以下字符串转换为Unix纪元时间戳?
Thu, 03 Oct 2013 14:55:44 GMT
I can pull in the local http timestamp via the following: 我可以通过以下方式获取本地http时间戳:
In [53]: now = datetime.now()
In [54]: stamp = mktime(now.timetuple())
In [55]: print format_date_time(stamp)
Thu, 03 Oct 2013 16:24:59 GMT
and how would i convert the resulting unix timestamp back to the above format? 以及如何将所得的unix时间戳转换回上述格式?
Thanks! 谢谢!
Convert to timestamp: 转换为时间戳:
from datetime import datetime
ts = datetime.strptime("Thu, 03 Oct 2013 14:55:44 GMT", "%a, %d %b %Y %X %Z").strftime("%s")
print ts # '1380804944'
Convert back to the original format: 转换回原始格式:
from datetime import datetime
dtime = datetime.fromtimestamp(int('1380804944')).strftime("%a, %d %b %Y %X %Z GMT")
print dtime # 'Thu, 03 Oct 2013 14:55:44 '
>>> import time
>>> int(time.time())
1380817337
>>>
>>> import email
>>> time.mktime(email.utils.parsedate("Thu, 03 Oct 2013 14:55:44 GMT"))
1380804944.0
And back: 然后回来:
>>> f = 1380804944.0
>>> email.utils.formatdate(f, False, True)
'Thu, 03 Oct 2013 12:55:44 GMT'
I answered a very similar question earlier today here . 我今天早些时候在这里回答了一个非常类似的问题。 Let me know if that works for you.
让我知道这是否适合您。
Basically you need to look at the time.strptime()
and time.mktime()
functions. 基本上,您需要查看
time.strptime()
和time.mktime()
函数。
In your case, the format specifier would be: 在您的情况下,格式说明符为:
time.strptime("Thu, 03 Oct 2013 14:55:44 GMT", "%a, %d %b %Y %X %Z")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.