Get the GMT time given date and UTC offset in python

荒凉一梦 提交于 2019-11-30 18:32:26

问题


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 to convert it to the GMT time

So the result will be '1998-10-24 09:31:15'


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/4044863/get-the-gmt-time-given-date-and-utc-offset-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!