How to get the common name for a pytz timezone eg.

2019-01-18 01:48发布

问题:

Given a pytz timezone for a particular user(calculated from his offset), i want to display the common name for that timezone. I'm assuming people are more accustomed to seeing EST or PST instead of spelled out like America/NewYork.

Does pytz give me those standard names somewhere, or will i have to manually do this via a table? This could potentially get messy, since for example places are EST in a season and shift to showing EDT during others.

回答1:

Given a pytz timezone for a particular user(calculated from his offset), i want to display the common name for that timezone. I'm assuming people are more accustomed to seeing EST or PST instead of spelled out like America/NewYork.

If you need this derived from a datetime object localized with pytz...

>>> import pytz as tz
>>> from datetime import datetime as dt
>>> CT = tz.timezone('America/Chicago')
>>>
>>> summer_day = dt(2010, 7, 4, 0, 1, 1)
>>> bar = CT.localize(summer_day, is_dst=None)
>>> bar.tzname()
'CDT'
>>>
>>> christmas = dt(2010, 12, 25, 0, 1, 1)
>>> foo = CT.localize(christmas, is_dst=None)
>>> foo.tzname()
'CST'
>>> 


回答2:

You can use the tzname() method of tzinfo instances:

>>> tz = timezone('America/St_Johns')
>>> normal = datetime(2009, 9, 1)
>>> tz.tzname(normal, is_dst=False)
'NDT'


回答3:

If you are looking for the abbreviations then there are a few ways that come to mind.

First would be:

>>> from pytz import timezone
>>> eastern = timezone('US/Eastern')
>>> eastern._tzname
'EST'

Although since that references a property with the preceding single underscore it may be considered private and might not be the best place to grab it. The other would be from a localized datetime object.

>>> from datetime import datetime
>>> loc_dt = eastern.localize(datetime.now())
>>> loc_dt.strftime('%Z')
'EST'