Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

python - Why doesn't pytz localize() produce a datetime object with tzinfo matching the tz object that localized it?

Is there anyone who can help me understand what's going on here?

import pytz
from datetime import datetime
tz = pytz.timezone('Europe/Berlin')
print repr(tz)
# <DstTzInfo 'Europe/Berlin' LMT+0:53:00 STD>
dt = datetime(2011, 1, 3, 18, 40)
result = tz.localize(dt)
print repr(result.tzinfo)
# <DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>
assert result.tzinfo == tz, "Why aren't these the same timezone?"

My understanding was that the localize() method on a pytz timezone object would take a naive datetime object, and add a tzinfo property that matches the timezone object performing the localization. That does not appear to be happening in this case.

Clearly, there's something I'm misunderstanding about timezones, or about the way that pytz handles timezones. Can anyone explain?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They are the same time zone - "Europe/Berlin".

When you are printing them, the output includes the abbreviation and offset that applies at that particular point in time.

If you examine the tz data sources, you'll see:

# Zone  NAME            GMTOFF   RULES       FORMAT   [UNTIL]
Zone    Europe/Berlin   0:53:28  -           LMT      1893 Apr
                        1:00     C-Eur       CE%sT    1945 May 24 2:00
                        1:00     SovietZone  CE%sT    1946
                        1:00     Germany     CE%sT    1980
                        1:00     EU          CE%sT

So it would appear that when the time zone has not localized a datetime, then it just uses the first entry.

It would also appear that pytz doesn't retain the extra 28 seconds from the original local mean time deviation - but that doesn't matter unless you are working with dates in Berlin before April 1893.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...