Skip to content Skip to sidebar Skip to footer

Python Datetime Strptime() Does Not Match Format

I get the following error in which you can see the time data and the format I am using time data '20:07:35 EEDT Wed Mar 31 2021' does not match format '%H:%M:%S %Z %a %b %d %Y' I u

Solution 1:

import datetime

time = '20:07:35 EEDT Wed Mar 31 2021'time = time.replace('EEDT', '+0300')
datetime.datetime.strptime(time, '%H:%M:%S %z %a %b %d %Y')

Solution 2:

you can map the abbreviated time zone to a IANA time zone name by dateutil's parser:

import dateutil

s = '20:07:35 EEDT Wed Mar 31 2021'

tzmapping = {"EEDT": dateutil.tz.gettz('Europe/Athens'),
             "EEST": dateutil.tz.gettz('Europe/Athens')} # add more if needed...

dtobj = dateutil.parser.parse(s, tzinfos=tzmapping)

that will give you

dtobj
# >>> datetime.datetime(2021, 3, 31, 20, 7, 35, tzinfo=tzfile('Europe/Athens'))
dtobj.utcoffset()
# >>> datetime.timedelta(seconds=10800) # UTC+3

Note that timedelta arithmetic works correctly, i.e. includes DST changes:

from datetime import timedelta
dtobj -= timedelta(7) # DST change: dtobj is now EEST, UTC+2
dtobj.utcoffset()
# >>> datetime.timedelta(seconds=7200)

Solution 3:

Problem is with EEDT. If you ignore EEDT(quickfix, not ideal), then your code may look like:

text = '20:07:35 EEDT Wed Mar 31 2021';
fmt = '%H:%M:%S EEDT %a %b %d %Y';
datetime.strptime(text, fmt)

--edit--

parsing datetime with timezone is difficult to pure datetime module. I'm not big expert, but pytz or python-datetutil should be good choice, according to this page: https://medium.com/@nqbao/python-timezone-and-daylight-savings-e511a0093d0

Post a Comment for "Python Datetime Strptime() Does Not Match Format"