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


Groups > comp.lang.python > #64954 > unrolled thread

Re: UTC "timezone" causing brain explosions

Started byBen Finney <ben+python@benfinney.id.au>
First post2014-01-30 09:44 +1100
Last post2014-01-30 09:44 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: UTC "timezone" causing brain explosions Ben Finney <ben+python@benfinney.id.au> - 2014-01-30 09:44 +1100

#64954 — Re: UTC "timezone" causing brain explosions

FromBen Finney <ben+python@benfinney.id.au>
Date2014-01-30 09:44 +1100
SubjectRe: UTC "timezone" causing brain explosions
Message-ID<mailman.6100.1391035514.18130.python-list@python.org>
Skip Montanaro <skip@pobox.com> writes:

> Following up on my earlier note about UTC v. GMT, I am having some
> trouble grokking attempts to convert a datetime into UTC.

For what it's worth, you're not alone. Time zones are a hairy beast to
manage, made all the more difficult because national politicians
continually fiddle with them which means they can't just be a built-in
part of the Python standard library.

> Consider these three values:
>
> >>> import pytz
> >>> UTC = pytz.timezone("UTC")
> >>> UTC
> <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?

Not really :-) You avoid the pain if you never create naive datetime
values in the first place.

Instead, specify the timezone for the value you're creating::

    >>> now = datetime.datetime.now(tz=LOCAL_TZ)
    >>> now
    datetime.datetime(2014, 1, 29, 16, 35, 7, 900526, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>)

That way the value will respond correctly to requests to convert it to
whatever timezone you specify::

    >>> MELBOURNE = pytz.timezone("Australia/Melbourne")
    >>> now.astimezone(MELBOURNE)
    datetime.datetime(2014, 1, 30, 9, 35, 7, 900526, tzinfo=<DstTzInfo 'Australia/Melbourne' EST+11:00:00 DST>)
    >>> now.astimezone(UTC)
    datetime.datetime(2014, 1, 29, 22, 35, 7, 900526, tzinfo=<UTC>)
    >>> now.astimezone(LOCAL_TZ)
    datetime.datetime(2014, 1, 29, 16, 35, 7, 900526, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>)

-- 
 \      “We tend to scoff at the beliefs of the ancients. But we can't |
  `\        scoff at them personally, to their faces, and this is what |
_o__)                                         annoys me.” —Jack Handey |
Ben Finney

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web