0
votes

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 used the directives from here and I see that the format matches the description of each directive. Can you see what is the issue here?

3
The problem seems to be the timezone - peter
It doesn'T accept 'EEDT'. It works however for 'UTC' - peter
@peter %Z accepts GMT or UTC but it doesn't parse to aware datetime. That can lead to unexpected results since you might expect UTC but you get local time since Python treats naive datetime like that. - MrFuppes

3 Answers

2
votes
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')
1
votes

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)
1
votes

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