2014-12-27 39 views
0

我試圖創建一個名爲to_timezone是 將採取區名稱作爲字符串函數,然後轉換「啓動」 到時區,使用pytz的時區...我希望它返回一個新的日期時間。創建具有PYTZ的時區​​功能

我希望它成爲'tz'來的任何時區。 我不想硬編碼'pytz時區對象' 我該如何實現這一目標?
這裏是我的代碼:

import datetime 

import pytz 

starter = pytz.utc.localize(datetime.datetime(2015, 10, 21, 23, 29)) 

def to_timezone(tz): 
    tz_utc = pytz.timezone('#pytz timezone object') 
    starter = tz_utc.astimezone 
    return starter 

回答

0

如果tz是從TZ數據庫中的時區的名稱,如"America/New_York"那麼你可以直接將它傳遞給pytz.timezone和使用astimezone()normalize()方法,將一個知道DateTime對象startertz時區:

def to_timezone(aware_dt, zonename): 
    tz = pytz.timezone(zonename) 
    return tz.normalize(aware_dt.astimezone(tz)) 

例:

starter = datetime.datetime(2015, 10, 21, 23, 29, tzinfo=pytz.utc) 
print(to_timezone(starter, "America/Los_Angeles")) 
# -> 2015-10-21 16:29:00-07:00 
0

我不知道如果我理解正確,但你可以只通過什麼來作爲tzpytz.timezone

def to_timezone(tz): 
    tz_utc = pytz.timezone(tz) 

,所以你可以例如致電to_timezone('Europe/London')