Python Time-parsing Fails, When Tz Is In The Environment
The following simple script: from datetime import datetime as DT ts = 'Mon Aug 17 12:49:28 EDT 2020' fmt = '%a %b %d %H:%M:%S %Z %Y' dts = DT.strptime(ts, fmt) print(dts) works
Solution 1:
I suggest using dateutil
's parser.parse with a time zone mapping dict:
import dateutil
ts = 'Mon Aug 17 12:49:28 EDT 2020'# add more time zone names / abbreviations as key-value pairs here:
tzmapping = {'EDT': dateutil.tz.gettz('US/Eastern')}
dt = dateutil.parser.parse(ts, tzinfos=tzmapping)
print(dt)
print(repr(dt))
# 2020-08-17 12:49:28-04:00# datetime.datetime(2020, 8, 17, 12, 49, 28, tzinfo=tzfile('US/Eastern'))
Time zone name abbreviations are inherently ambiguous and won't be parsed by %Z
. Exceptions are UTC and GMT - however, also be careful with that! %Z accepts e.g. a literal "UTC" but it doesn't result in an aware datetime object. Again, dateutil's parser does a better job than the standard lib's datetime.strptime.
Post a Comment for "Python Time-parsing Fails, When Tz Is In The Environment"