4

I want to convert this string datetimestring = 'Fri, 08 Jun 2012 22:40:26 GMT' to timestamp using python.

I tried

 timestamp = time.mktime(time.strptime(datetimestring, '%a, %d %B %Y %H:%M:%S GMT'))

but reports regex error.

2
  • 3
    Don't just tell us you got an error, give us the actual error. Commented Jun 9, 2012 at 0:47
  • 1
    Especially because there is no regex in the code you pasted :-) Commented Jun 9, 2012 at 0:54

3 Answers 3

6

You're using %B, which corresponds to the full month name, but you only have the abbreviated name. You should use %b instead:

>>> import time
>>> datetimestring = 'Fri, 08 Jun 2012 22:40:26 GMT' 
>>> timestamp = time.mktime(time.strptime(datetimestring, '%a, %d %B %Y %H:%M:%S GMT'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 454, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'Fri, 08 Jun 2012 22:40:26 GMT' does not match format '%a, %d %B %Y %H:%M:%S GMT'
>>> timestamp = time.mktime(time.strptime(datetimestring, '%a, %d %b %Y %H:%M:%S GMT'))
>>> timestamp
1339209626.0
Sign up to request clarification or add additional context in comments.

Comments

4

import time import dateutil.parser as dateparser

datetimestring = 'Fri, 08 Jun 2012 22:40:26 GMT'
dt = dateparser.parse(datetimestring)
timestamp = int(time.mktime(dt.timetuple()))

3 Comments

This solution converts different string date formats, so you don't care about the formatting.
This solution works great! But, i think needed to install this: pypi.python.org/pypi/dateparser
I think this is better solution because it is not need specified format of date, vote up
0

You can use dateparser for this purpose.

import dateparser >>> dateparser.parse('Fri, 08 Jun 2012 22:40:26 GMT') datetime.datetime(2012, 6, 8, 22, 40, 26)

Comments

Your Answer

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