views:

67

answers:

2

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  A: 

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)
SilentGhost
@SilentGhost - +1, thanks for the better answer. `time.strftime("%Y-%m-%d %H:%M:%S", t)` will give the desired output. Turns out that parsing using `time.strptime()` doesn't work so great with %Z for time zones like "+0100".
bstpierre
@bstpierre, I've never understood why `datetime` doesn't include better support for time zones. It seems like such an essential requirement.
Mark Ransom
@Mark Ransom - I was talking about `time`, but I agree with your comment. Dealing with timezones properly is not easy.
bstpierre
@bstpierre, I was talking about `datetime` as a module not a class, so my comment included `time` as well.
Mark Ransom
A: 

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
Mark Ransom
What if offset is negative?
adw
@adw, good point, there was an error when the offset was negative and the minutes were non-zero, e.g. '-0130'. Fixed.
Mark Ransom
@Mark Ransom: Nope, not fixed. For example, compare `offset = -100` with `offset = -101`.
adw
@adw, thanks again, that was very sloppy of me. I've tried a different approach this time, I think it's finally right.
Mark Ransom