问题
I have written this code to convert a unusual time into EPOCH:
x = 'Mon Jul 25 19:04:30 GMT+01:00 2016'
print(datetime.strptime(x, '%a %b %d %H:%M:%S %Z%z %Y').strftime('%s'))
However, it returns the error ValueError: time data 'Mon Jul 25 19:04:30 GMT+01:00 2016' does not match format '%a %b %d %H:%M:%S %Z%z %Y'
The problem is something to do with the timezone. What have I done wrong?
回答1:
Your timezone format has an extra :
inside which causes the format mismatching error, you can remove the last :
from the string firstly and then parse it:
import re
from datetime import datetime
x1 = re.sub(r":(?=[^:]+$)", "", x) # remove the last semi colon
datetime.strptime(x1, '%a %b %d %H:%M:%S %Z%z %Y').strftime('%s')
# '1469487870'
回答2:
If you use dateutil instead of datetime.strptime it seems to work:
from dateutil import parser
parser.parse("Mon Jul 25 19:04:30 GMT+01:00 2016")
>> datetime.datetime(2016, 7, 25, 19, 4, 30, tzinfo=tzoffset(None, -3600))
来源:https://stackoverflow.com/questions/41782874/valueerror-parsing-time-string