Getting timezone from dateutil.parser.parse in Python

17.6k views Asked by At

Trying to parse the datetime string with timezone info and get the utc offset

from dateutil.parser import parse as parse_date
s = '2017-08-28 06:08:20,488 CDT'
dt = parse_date(s)
print(dt.utcoffset())  # prints `None`

Why is utcoffset returning None rather than -5 as offset?

1

There are 1 answers

0
TheoretiCAL On BEST ANSWER

From the datetime docs:

If tzinfo is None, returns None

In your code, dt.tzinfo is None, so the timezone information was not parsed by parse_date into the dt. Your datetime dt is "naive" (has no timezone information).

As per the dateutil docs, You can pass your own timezone information to parse_date as either a tzoffset or tzfile:

tzinfos = {"CDT": -21600}
dt = parse_date('2017-08-28 06:08:20 CDT', tzinfos=tzinfos)
dt.tzinfo #tzoffset('CDT', -21600)

from dateutil import tz
tzinfos = {"CDT": tz.gettz('US/Central')}
dt = parse_date('2017-08-28 06:08:20 CDT', tzinfos=tzinfos)
dt.tzinfo #tzfile('/usr/share/zoneinfo/US/Central')

Or you can encode the timezone offset into the string:

dt = parse_date('2017-08-28 06:08:20-06:00')
dt.tzinfo #tzoffset(None, -21600)