Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #64955

Re: UTC "timezone" causing brain explosions

References <CANc-5UyOGNWdug-JvXe_RMn9V7BCGFyZ0NwtSjFMFaW1f_wfhw@mail.gmail.com>
Date 2014-01-29 14:52 -0800
Subject Re: UTC "timezone" causing brain explosions
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.6101.1391035971.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Jan 29, 2014 at 1:52 PM, Skip Montanaro <skip@pobox.com> wrote:
> Following up on my earlier note about UTC v. GMT, I am having some
> trouble grokking attempts to convert a datetime into UTC. Consider
> these three values:
>
>>>> import pytz
>>>> UTC = pytz.timezone("UTC")
>>>> LOCAL_TZ = pytz.timezone("America/Chicago")
>>>> LOCAL_TZ
> <DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>
>>>> now = datetime.datetime.now()
>>>> now
> datetime.datetime(2014, 1, 29, 15, 39, 35, 263666)
>
> All well and good, right? The variable "now" is a naive datetime
> object. I happen to be sitting in a chair in the city of Chicago, so
> let's call it what it is, a datetime in the America/Chicago timezone:
>
>>>> s = LOCAL_TZ.localize(now)
>>>> s
> datetime.datetime(2014, 1, 29, 15, 39, 35, 263666, tzinfo=<DstTzInfo
> 'America/Chicago' CST-1 day, 18:00:00 STD>)
>
> That looks good to me. Now, let's normalize it to UTC:

I don't think .normalize() doesn't do what you think it does; it's
related to timezones with DST.
I believe you want datetime.astimezone() instead.

>>>> t = UTC.normalize(s)
>>>> t
> datetime.datetime(2014, 1, 29, 15, 39, 35, 263666, tzinfo=<UTC>)
>>>> t.hour
> 15
>
> WTF? Why isn't the t.hour == 21?

Because you didn't actually perform a proper timezone conversion:
>>> t = s.astimezone(UTC)
>>> t
datetime.datetime(2014, 1, 29, 21, 39, 35, 263666, tzinfo=<UTC>)
>>> t.hour == 21
True

<snip>
> That looks correct, but I don't understand why I don't get hour==21
> out of the UTC.normalize call. It's like it's a no-op.

It is indeed a no-op:
"You can take shortcuts when dealing with the UTC side of timezone
conversions. normalize() and localize() are not really necessary when
there are no daylight savings time transitions to deal with."
    -- http://pytz.sourceforge.net

Cheers,
Chris

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: UTC "timezone" causing brain explosions Chris Rebert <clp2@rebertia.com> - 2014-01-29 14:52 -0800

csiph-web