2010-10-28 162 views
3

偏移,我有以下格式'%Y%m%d%H%M%S'的例如'19981024103115' 日期字符串和UTC的另一個字符串,例如本地偏差定日期和UTC '+0100'獲取GMT時間蟒蛇

什麼是最好的方式在Python將其轉換爲GMT時間

那麼結果將是'1998-10-24 09:31:15'

回答

3

您可以使用該dateutil

>>> from dateutil.parser import parse 
>>> dt = parse('19981024103115+0100') 
>>> dt 
datetime.datetime(1998, 10, 24, 10, 31, 15, tzinfo=tzoffset(None, 3600)) 
>>> dt.utctimetuple() 
time.struct_time(tm_year=1998, tm_mon=10, tm_mday=24, tm_hour=9, tm_min=31, tm_sec=15, tm_wday=5, tm_yday=297, tm_isdst=0) 
+0

+1,感謝您的更好回答。 'time.strftime(「%Y-%m-%d%H:%M:%S」,t)'會給出所需的輸出。事實證明,使用'time.strptime()'進行分析對於時區「+0100」等時區的%Z效果不佳。 – bstpierre 2010-10-28 16:49:46

+0

@bstpierre,我從來沒有理解爲什麼'datetime'不包括更好的時區支持。這似乎是這樣一個基本要求。 – 2010-10-28 17:18:51

+0

@Mark Ransom - 我在談論'時間',但我同意你的評論。正確處理時區並不容易。 – bstpierre 2010-10-28 17:28:19

0

只要您知道時間偏移將始終爲4位數形式,這應該工作。

def MakeTime(date_string, offset_string): 
    offset_hours = int(offset_string[0:3]) 
    offset_minutes = int(offset_string[0] + offset_string[3:5]) 
    gmt_adjust = datetime.timedelta(hours = offset_hours, minutes = offset_minutes) 
    gmt_time = datetime.datetime.strptime(date_string, '%Y%m%d%H%M%S') - gmt_adjust 
    return gmt_time 
+0

如果偏移量是負值會怎麼樣? – adw 2010-10-28 17:30:29

+0

@adw,好點,當偏移量爲負數且分鐘不爲零時出現錯誤,例如, '-0130'。固定。 – 2010-10-28 18:05:22

+0

不,不是固定的。例如,比較'offset = -100'和'offset = -101'。 – adw 2010-10-28 18:15:05