偏移,我有以下格式'%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