datetime, tzinfo ... strange conversion?

T

Tino Lange

Hi!

I'm surprised about the following code, maybe you can give me a hint whether
that's bug or feature? I'm just trying to convert local time to GMT and one
method gives a strange result:

######################
#! /usr/bin/env python

import datetime, pytz

_tz_utc = pytz.timezone("UTC")
_tz_germany = pytz.timezone("Europe/Berlin")

local = datetime.datetime.now(_tz_germany)
print "Local: ", local

gmt = local.astimezone(_tz_utc)
print "GMT (1)", gmt

gmt = datetime.datetime.combine(local.date(), local.timetz()).astimezone(_tz_utc)
print "GMT (2)", gmt

gmt = datetime.datetime.combine(datetime.date.today(),
datetime.time(local.hour, local.minute, local.second, local.microsecond,
_tz_germany)).astimezone(_tz_utc)
print "GMT (3)", gmt

gmt = datetime.datetime.combine(datetime.date.today(),
datetime.time(local.hour, local.minute, local.second, local.microsecond,
local.tzinfo)).astimezone(_tz_utc)
print "GMT (4)", gmt

print "_tz_germany:", _tz_germany, "(id: %s)" % id(_tz_germany), ",
local.tzinfo:", local.tzinfo, "(id: %s)" % id(local.tzinfo)

######################

Result:
tlange@tinux:~/is.work/Scripts$ ./timeconv.py
Local: 2006-04-01 20:09:26.469445+02:00
GMT (1) 2006-04-01 18:09:26.469445+00:00
GMT (2) 2006-04-01 18:09:26.469445+00:00
GMT (3) 2006-04-01 19:09:26.469445+00:00
GMT (4) 2006-04-01 18:09:26.469445+00:00
_tz_germany: Europe/Berlin (id: -1212869684) , local.tzinfo: Europe/Berlin
(id: -1212868756)

--> Why is GMT (3) wrong?

Cheers,

Tino
 
L

Lawrence D'Oliveiro

Tino Lange said:
--> Why is GMT (3) wrong?

At a guess, it's because there's nothing in the parameters passed to
indicate that daylight saving is currently in effect.

Tip: always do your date/time calculations as far as possible in UTC.
Only convert to local time at the last possible step, before displaying
results to the user.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top