偏移,我有以下格式'%Y%m%d%H%M%S'
的例如'19981024103115'
日期字符串和UTC的另一個字符串,例如本地偏差定日期和UTC '+0100'
獲取GMT時間蟒蛇
什麼是最好的方式在Python將其轉換爲GMT時間
那麼結果將是'1998-10-24 09:31:15'
偏移,我有以下格式'%Y%m%d%H%M%S'
的例如'19981024103115'
日期字符串和UTC的另一個字符串,例如本地偏差定日期和UTC '+0100'
獲取GMT時間蟒蛇
什麼是最好的方式在Python將其轉換爲GMT時間
那麼結果將是'1998-10-24 09:31:15'
您可以使用該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)
只要您知道時間偏移將始終爲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
+1,感謝您的更好回答。 'time.strftime(「%Y-%m-%d%H:%M:%S」,t)'會給出所需的輸出。事實證明,使用'time.strptime()'進行分析對於時區「+0100」等時區的%Z效果不佳。 – bstpierre 2010-10-28 16:49:46
@bstpierre,我從來沒有理解爲什麼'datetime'不包括更好的時區支持。這似乎是這樣一個基本要求。 – 2010-10-28 17:18:51
@Mark Ransom - 我在談論'時間',但我同意你的評論。正確處理時區並不容易。 – bstpierre 2010-10-28 17:28:19