Reputation:
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.
Upvotes: 4
Views: 13282
Reputation:
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)
Upvotes: 0
Reputation: 702
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()))
Upvotes: 4
Reputation: 353059
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
Upvotes: 6