470,864 Members | 2,023 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,864 developers. It's quick & easy.

datetime, tzinfo ... strange conversion?

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

Apr 1 '06 #1
1 2498
In article <e0**********@newsreader3.netcologne.de>,
Tino Lange <tl*****@nexgo.de> wrote:
--> 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.
Apr 3 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by John Hunter | last post: by
4 posts views Thread by Max M | last post: by
3 posts views Thread by Harald Hanche-Olsen | last post: by
1 post views Thread by Adam Monsen | last post: by
1 post views Thread by James | last post: by
reply views Thread by David Pratt | last post: by
4 posts views Thread by Philippe Martin | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.