2011-09-18 43 views
7

我有一個要求,從本地時間戳到UTC然後回到本地時間戳。python/pytz問題從本地時區轉換爲UTC然後返回

奇怪的是,當從UTC轉換回本地時,python決定它是PDT而不是原來的PST,因此轉換後的日期已經增加了一個小時。有人可以向我解釋發生了什麼或我做錯了什麼嗎?

from datetime import datetime 
from pytz import timezone 
import pytz 

DATE_FORMAT = '%Y-%m-%d %H:%M:%S %Z%z' 

def print_formatted(dt): 
    formatted_date = dt.strftime(DATE_FORMAT) 
    print "%s :: %s" % (dt.tzinfo, formatted_date) 


#convert the strings to date/time 
date = datetime.now() 
print_formatted(date) 

#get the user's timezone from the pofile table 
users_timezone = timezone("US/Pacific") 

#set the parsed date's timezone 
date = date.replace(tzinfo=users_timezone) 
date = date.astimezone(users_timezone) 
print_formatted(date) 

#Create a UTC timezone 
utc_timezone = timezone('UTC') 
date = date.astimezone(utc_timezone) 
print_formatted(date) 

#Convert it back to the user's local timezone 
date = date.astimezone(users_timezone) 
print_formatted(date) 

這裏是輸出:

None :: 2011-09-18 18:24:23 
US/Pacific :: 2011-09-18 18:24:23 PST-0800 
UTC :: 2011-09-19 02:24:23 UTC+0000 
US/Pacific :: 2011-09-18 19:24:23 PDT-0700 

回答

6

變化

date = date.replace(tzinfo=users_timezone) 

date = users_timezone.localize(date) 

localize調整爲夏令時,replace確實ñ OT。有關更多信息,請參閱the docs

+0

謝謝修復它。 – user578888

相關問題