If you are using Python 2 or early versions of Python 3 (3.0 and 3.1), you can use the dateutil
library for converting a string to a timezone aware object.
The code to do this is simple:
>>> import dateutil.parser
>>> dt = dateutil.parser.parse('2016-08-01 13:39:00+05:30')
>>> dt
datetime.datetime(2016, 8, 1, 13, 39, tzinfo=tzoffset(None, 19800))
If you are using Python 3.2 or later, the %z
option has been added as a formatting option when parsing a date. You can accomplish this task without using dateutil
in these versions by doing this:
>>> import datetime
>>> dt = datetime.datetime.strptime('2016-08-01 13:39:00+0530', "%Y-%m-%d %H:%M:%S%z")
>>> dt
datetime.datetime(2016, 8, 1, 13, 39, tzinfo=datetime.timezone(datetime.timedelta(0, 19800)))
Unfortunately, you do have to strip the colon (:
) from the offset for this to work as expected.