3

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!

4 Answers 4

3
>>> import time
>>> int(time.time())
1380817337
>>> 
Sign up to request clarification or add additional context in comments.

Comments

3

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 '

Comments

3
>>> 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'

Comments

1

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

2 Comments

Does not quite work for me.... print time.strptime("Thu, 03 Oct 2013 16:24:59 GMT") returns: ValueError: time data 'Thu, 03 Oct 2013 16:24:59 GMT' does not match format '%a %b %d %H:%M:%S %Y'
@Clustermagnet Updated answer with the exact function call you would need to use. You missed the format specifier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.