Parsing Time String ValueError

I wrote this code to convert unusual time to 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 an 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 with the time zone. What did I do wrong?

+4
source share
2 answers

There is an additional :one in your time zone format , inside of which a format mismatch error occurs, you can first remove the last one :from the line and then analyze 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'
+3
source

If you use dateutil instead of datetime.strptime, this works:

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))
+2
source

Source: https://habr.com/ru/post/1667444/


All Articles