Alex Cory
Alex Cory

Reputation: 11845

How to get timezone from datetime string in python?

I have a date string that looks like this Tue Jul 19 2016 14:00:00 GMT-0700 (PDT). Is there a library or function that could do something like this?

print get_tz('Tue Jul 19 2016 14:00:00 GMT-0700 (PDT)')
'US/Pacific'

Upvotes: 6

Views: 8934

Answers (2)

Paul
Paul

Reputation: 10863

I agree with @MattJohnson that you need to be very careful when parsing short timezone names to tzinfo objects. However, if you have a specific context where only one reading makes sense (e.g. you are parsing timestamps generated in the United States), you can use the tzinfos argument to python-dateutil's parse function.

Here is an example on how it is used:

from dateutil import tz
from dateutil.parser import parse

ET = tz.gettz('US/Eastern')
CT = tz.gettz('US/Central')
MT = tz.gettz('US/Mountain')
PT = tz.gettz('US/Pacific')

us_tzinfos = {'CST': CT, 'CDT': CT,
              'EST': ET, 'EDT': ET,
              'MST': MT, 'MDT': MT,
              'PST': PT, 'PDT': PT}

dt_est = parse('2014-01-02 04:00:00 EST', tzinfos=us_tzinfos)
# >>> dt_est.tzinfo
# tzfile('/usr/share/zoneinfo/US/Eastern')

dt_pst = parse('2016-03-11 16:00:00 PST', tzinfos=us_tzinfos)
# >>> dt_pst.tzinfo
# tzfile('/usr/share/zoneinfo/US/Pacific')

Upvotes: 3

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241420

In general, you'll have to be careful about mapping time zone abbreviations to time zone identifiers. There's not a one-to-one mapping. For example, CST could be Central Standard Time, China Standard Time, or Cuba Standard Time.

Since you have both an offset and an abbreviation, you might be able to refine it a bit further, but you'll still have ambiguities. For example, if the string contained GMT+02:00 (EET), that could be any of the locations listed here, some of which use EET year-round, others of which use EET in the winter and EEST in the summer. Of those that use EEST, not all of them start and end at the same time.

Each variation creates a different time zone identifier. For example, Europe/Bucharest, Europe/Istanbul, Europe/Chisinau and Asia/Amman, all use EET and EEST, but all have slightly different transition dates or times.

Even when the current transitions align, they may have been different historically. For example, Europe/Athens and Europe/Helsinki may look the same at first, until you consider that Helsinki did not observe EEST in 1980.

These concerns will affect any library or function that attempts to resolve a time zone abbreviations and/or offsets to specific time zones, regardless of programming language.

Upvotes: 2

Related Questions