Question

I have been banging my head against Google and SO and not getting anywhere, but I am sure it has been answered a hundred times and is just buried.

I am receiving a time from a soap service and need to convert it to the time specified in the timezone offset, so

2014-02-06 13:30:00-05:00

should be

2014-02-06 08:30:00

so I can format and display the correct time for the event.

I have been playing with dateutil and pytz to no avail. Can anyone point me to where I should be looking? Everything I have found changes the timezone info, but it won't change the hour to where it belongs.

Was it helpful?

Solution

dateutil handles the format straight out of the box:

from dateutil import parser

dt = parser.parse('2014-02-06 13:30:00-05:00')

Now you have a timezone-aware datetime.datetime() value, including displaying it as a UTC ISO8601 timestamp:

from dateutil import tz

print dt.astimezone(tz.tzutc()).isoformat(' ')

This uses datetime.datetime.astimezone() to transform the timezone-aware datetime value to the UTC timezone.

Demo:

>>> from dateutil import parser
>>> from dateutil import tz
>>> dt = parser.parse('2014-02-06 13:30:00-05:00')
>>> print dt.astimezone(tz.tzutc()).isoformat(' ')
2014-02-06 18:30:00+00:00

This includes a timezone offset (of +00:00), you can use the datetime.datetime.strftime() method to format the string differently if desired.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top