2011-09-27 82 views
0

我有一個字符串形式'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?

+0

您需要調用'date_time.localize'。這是這裏完全缺失的唯一基本成分。 – wberry

回答

3

下面的代碼片段會做什麼,你想

def convert(dte, fromZone, toZone): 
    fromZone, toZone = pytz.timezone(fromZone), pytz.timezone(toZone) 
    return fromZone.localize(dte, is_dst=True).astimezone(toZone) 

這裏的關鍵部分是通過is_dst的本地化方法。

+0

基於文檔,似乎is_dst標誌可能不會解釋並提供期望值:>>> dt = datetime(2002,10,27,1,30,0) >>> dt1 = eastern.localize( dt,is_dst = True) >>> dt1.strftime(fmt) '2002-10-27 01:30:00 EDT-0400' >>> dt2 = eastern.localize(dt,is_dst = False) > >> dt2.strftime(fmt) '2002-10-27 01:30:00 EST-0500' –

+0

'is_dst'參數是可選的,除非在模糊時間的情況下(即在「回退」期間當地時區中的同一小時發生兩次)。剩下的時間轉換將在沒有它的情況下工作。該參數告訴'pytz'夏時制是否有效,或者您所提供的'datetime'對象是否有效。 – wberry

0

simple-date寫使轉換這樣微不足道的(你需要版本0.2.1或更高版本此):

>>> from simpledate import * 
>>> SimpleDate('20111014T090000', tz='America/Los_Angeles').timestamp 
1318608000.0 
0

如果你的程序改變全球時區(臨時)允許,你可以也可以這樣做:

os.environ['TZ'] = 'America/Los_Angeles' 
t = [2011, 10, 14, 9, 0, 0, 0, 0, -1] 
return time.mktime(time.struct_time(t)) 

預期的1318608000.0被返回。

0

給定字符串轉換成天真DateTime對象:

>>> from datetime import datetime 
>>> naive_dt = datetime.strptime('20111014T090000', '%Y%m%dT%H%M%S') 
>>> naive_dt 
datetime.datetime(2011, 10, 14, 9, 0) 

要附加的時區(使它成爲意識到DateTime對象):

>>> import pytz 
>>> tz = pytz.timezone('America/Los_Angeles') 
>>> local_dt = tz.localize(naive_dt, is_dst=None) 
>>> print(local_dt.strftime("%Y-%m-%d %H:%M:%S %Z%z")) 
2011-10-14 09:00:00 PDT-0700 

注:is_dst=None用來引發異常對於不存在或模糊的當地時代。

>>> (local_dt - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds() 
1318608000.0 

在你的問題的主要問題是:

要從認識DateTime對象得到POSIX時間戳

  1. 更換了tzinfo屬性,tz.localize應改爲使用
  2. mktime()作品與當地時間(您的計算機時區),而不是UTC。