Missing something about timezones

Ian Kelly ian.g.kelly at gmail.com
Mon Mar 14 12:20:55 EDT 2016


On Mon, Mar 14, 2016 at 9:32 AM, Skip Montanaro
<skip.montanaro at gmail.com> wrote:
> On Mon, Mar 14, 2016 at 10:26 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>> Why should it? You only asked pytz for the Chicago timezone. You
>> didn't ask for it relative to any specific time.
>
> Thanks. I thought using America/Chicago was supposed to automagically
> take into account transitions into and out of Daylight Savings. Is
> there some way to get that?

Use the timezone to localize a specific time, and then if it's
specifically the timezone that you're interested in, you can get it
from the datetime.

>>> from datetime import datetime
>>> import pytz
>>> tz = pytz.timezone('America/Chicago')
>>> tz
<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>
>>> dt = datetime.now()
>>> dt
datetime.datetime(2016, 3, 14, 10, 16, 40, 404608)
>>> loc_dt = tz.localize(dt)
>>> loc_dt
datetime.datetime(2016, 3, 14, 10, 16, 40, 404608, tzinfo=<DstTzInfo
'America/Chicago' CDT-1 day, 19:00:00 DST>)

Note that the above example is technically incorrect since
datetime.now() returns local time and I'm not in the Chicago timezone,
but it demonstrates the process.

Also, if you haven't already read the pytz documentation, you should.
http://pythonhosted.org/pytz/



More information about the Python-list mailing list