简体   繁体   中英

Converting http request time to unix timestamp in Python

Folks, How would I convert the following string to a unix epoch timestamp?

Thu, 03 Oct 2013 14:55:44 GMT

I can pull in the local http timestamp via the following:

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?

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.

In your case, the format specifier would be:

time.strptime("Thu, 03 Oct 2013 14:55:44 GMT", "%a, %d %b %Y %X %Z")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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