Skip to content Skip to sidebar Skip to footer

Get The Gmt Time Given Date And Utc Offset In Python

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 pytho

Solution 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)

Solution 2:

As long as you know that the time offset will always be in the 4-digit form, this should work.

defMakeTime(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

Post a Comment for "Get The Gmt Time Given Date And Utc Offset In Python"