views:

222

answers:

1

Hi Guy,

It's a bit weird it seems that when I want to get a timezone for Europe/Paris with pytz it gets me to the PMT timezone instead of GMT+1 when it seems to work for Europe/Berlin.

Not clear ? Well look at this snippet :

#!/usr/bin/python
import os
import datetime
from pytz.tzfile import build_tzinfo

base='/usr/share/zoneinfo/'
tz = build_tzinfo('Europe/Paris',
                  open(os.path.join(base,'Europe','Paris'), 'rb'))
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
print datetime.datetime(2009, 01, 30, 9, 00, tzinfo=tz).strftime(fmt)

tz = build_tzinfo('Europe/Berlin',
                  open(os.path.join(base,'Europe','Berlin'), 'rb'))

print datetime.datetime(2009, 01, 30, 9, 00, tzinfo=tz).strftime(fmt)

the output is :

2009-01-30 09:00:00 PMT+0009
2009-01-30 09:00:00 CET+0100

when really paris should be as well CET+1.

Constructing from datetime.datetime.now(tz) would get the thing right no matter what.

Anybody have an idea ?

+1  A: 

The docs say you can't use datetime.datetime(..., tzinfo) like you're doing:

Unfortunately using the tzinfo argument of the standard datetime constructors does not work with pytz for many timezones.

And curiously, despite all signs that the Europe/Paris timezone is wrong, when you actually use with localize as it recommends, it works nonetheless:

>>> tz= pytz.timezone('Europe/Paris')               # using built-in zoneinfo
>>> tz
<DstTzInfo 'Europe/Paris' PMT+0:09:00 STD>          # what? Pierre et Miquelon Time?
>>> datetime.datetime(2010,1,1,12,0,0, tzinfo=tz)
datetime.datetime(2010, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Europe/Paris' PMT+0:09:00 STD>) # bad
>>> tz.localize(datetime.datetime(2010,1,1,12,0,0))
datetime.datetime(2010, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>) # OK

Note that the tzinfo property of the localized datetime references a completely different object to the tz it was created from, sharing only the name.

It's a mystery to me why this is happening. It seems to be a problem with city files that understand multiple timezone names, but why you don't get the default timezone for a city until you call localize, I've no idea.

(To be honest I've never trusted Python's datetime and tzinfo stuff. Much prefer working with int UTC timestamps.)

bobince
On the whole, Python's timezone stuff is very poorly designed. The concept of "naive" times is useless and vastly overcomplicated; there should only be one type of datetime, and it should default to UTC, not "unknown" (naive).
Glenn Maynard