2013-06-04 21 views
0

我正在寫一些Python(Python 2.7.4(默認,2013年4月6日,19:54:46)[MSC v.1500 32 bit(Intel)]在win32上,Windows 7)需要處理時區的代碼。爲此,我使用了pytz庫(2012d版本),以便我使用easy_install更新安全端。pytz.timezone('Asia/Chongqing')行爲奇怪

我特別需要在中國四川省成都市表達時間。這是在'亞洲/重慶'時區,應該是比'歐洲/倫敦'(這是我當地的時區)+07:00小時

由於某些原因,當我在亞洲創建datetime.datetime/Chonqing'區域應用的偏移量是+07:06而不是我期望的+07:00。但是當我在另一個區域(紐約州)創建一個datetime.datetime時,它可以正常工作。

我認爲pytz數據庫是正確的,所以我做錯了什麼?我會很感激任何建議。

""" 
Fragment of code for messing about with (foreign) 
time-zones and datetime/ephem 
""" 

import datetime 
import pytz 

ChengduTZ = pytz.timezone('Asia/Chongqing') 
ParisTZ = pytz.timezone('Europe/Paris') 
LondonTZ = pytz.timezone('Europe/London') 
NewYorkTZ = pytz.timezone('America/New_York') 

MidnightInChengdu = datetime.datetime(2013, 6, 5, 0, 0, 0, 0, ChengduTZ) 
MidnightInNewYork = datetime.datetime(2013, 6, 5, 0, 0, 0, 0, NewYorkTZ) 

print("When it's midnight in Chengdu it's:") 
print(MidnightInChengdu) 
print(MidnightInChengdu.astimezone(LondonTZ)) 
print(MidnightInChengdu.astimezone(ParisTZ)) 
print(MidnightInChengdu.astimezone(NewYorkTZ)) 

print("\nWhen it's midnight in New York it's:") 
print(MidnightInNewYork) 
print(MidnightInNewYork.astimezone(LondonTZ)) 
print(MidnightInNewYork.astimezone(ParisTZ)) 
print(MidnightInNewYork.astimezone(ChengduTZ)) 

產生以下輸出:

When it's midnight in Chengdu it's: 
2013-06-05 00:00:00+07:06 
2013-06-04 17:54:00+01:00 
2013-06-04 18:54:00+02:00 
2013-06-04 12:54:00-04:00 

When it's midnight in New York it's: 
2013-06-05 00:00:00-05:00 
2013-06-05 06:00:00+01:00 
2013-06-05 07:00:00+02:00 
2013-06-05 13:00:00+08:00 
+0

可能重複的[Python日期時間對象顯示錯誤的時區偏移](https://stackoverflow.com/questions/6410971/python-datetime-object-show-wrong-timezone-offset) – Paul

回答

1

您需要使用.localize()方法把日期時間在正確的時區,否則歷史被錯誤地選擇了偏移:

ChengduTZ = pytz.timezone('Asia/Chongqing') 
MidnightInChengdu = ChengduTZ.localize(datetime.datetime(2013, 6, 5, 0, 0, 0, 0)) 
MidnightInNewYork = NewYorkTZ.localize(datetime.datetime(2013, 6, 5, 0, 0, 0, 0)) 

查看pytz documenation

不幸的是,對於許多時區,使用標準日期時間構造函數的tzinfo參數「不適用」pytz。

隨着這一變化,輸出變爲:

When it's midnight in Chengdu it's: 
2013-06-05 00:00:00+08:00 
2013-06-04 17:00:00+01:00 
2013-06-04 18:00:00+02:00 
2013-06-04 12:00:00-04:00 

When it's midnight in New York it's: 
2013-06-05 00:00:00-04:00 
2013-06-05 05:00:00+01:00 
2013-06-05 06:00:00+02:00 
2013-06-05 12:00:00+08:00 

注意,紐約偏移也是不正確。