I have a date string of the following format '%Y%m%d%H%M%S'
for example '19981024103115'
and another string of the UTC local offset for example '+0100'
What's the best way in python 开发者_如何学Pythonto convert it to the GMT time
So the result will be '1998-10-24 09:31:15'
You could use dateutil
for that:
>>> 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)
As long as you know that the time offset will always be in the 4-digit form, this should work.
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
精彩评论