Skip Montanaro <s...@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 -- https://mail.python.org/mailman/listinfo/python-list