Get the given GMT and UTC offset date in python

I have a date string of the following format, '%Y%m%d%H%M%S'for example, '19981024103115' and another string of local UTC offset, for example'+0100'

What is the best way in python to convert it to GMT

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

+3
source share
2 answers

You can use dateutilfor this:

>>> 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)
+3
source

As long as you know that the time offset will always be in 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
0
source

Source: https://habr.com/ru/post/1771959/


All Articles