我有一個字符串形式'20111014T090000'與關聯的時區ID(TZID = America/Los_Angeles),我想 轉換爲UTC時間在幾秒鐘與適當的抵消。正確轉換之間tz不知道時間,UTC和python工作時區
這個問題似乎是我的輸出時間偏離了1小時(這是在PST時,它應該是PDT)和我使用pytz幫助timezo
import pytz
def convert_to_utc(date_time)
# date_time set to '2011-10-14 09:00:00' and is initially unaware of timezone information
timezone_id = 'America/Los_Angeles'
tz = pytz.timezone(timezone_id);
# attach the timezone
date_time = date_time.replace(tzinfo=tz);
print("replaced: %s" % date_time);
# this makes date_time to be: 2011-10-14 09:00:00-08:00
# even though the offset should be -7 at the present time
print("tzname: %s" % date_time.tzname());
# tzname reports PST when it should be PDT
print("timetz: %s" % date_time.timetz());
# timetz: 09:00:00-08:00 - expecting offset -7
date_time_ms = int(time.mktime(date_time.utctimetuple()));
# returns '1318611600' which is
# GMT: Fri, 14 Oct 2011 17:00:00 GMT
# Local: Fri Oct 14 2011 10:00:00 GMT-7
# when expecting: '1318608000' seconds, which is
# GMT: Fri, 14 Oct 2011 16:00:00 GMT
# Local: Fri Oct 14 2011 9:00:00 GMT-7 -- expected value
我如何獲得正確的偏移量基於時區ID?
您需要調用'date_time.localize'。這是這裏完全缺失的唯一基本成分。 – wberry