简体   繁体   中英

How to convert String Datetime to timestamp in Python?

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.

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

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

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)

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