ValueError parsing time string

淺唱寂寞╮ 提交于 2019-12-10 16:37:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!