2010-10-28 166 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