John F.
John F.

Reputation: 4840

Converting ISO 8601 date format with timezone in python

I am attempting to convert the following date (2012-12-25T08:52:00-05:00) to a datetime object in python. However, I cannot figure out what the -05:00 part of the date is referencing. I am simply trying to perform the following:

datetime.datetime.strptime('2012-12-25T08:52:00-05:00','%Y-%m-%dT%H:%M:%S')

But this comes up with an expected 'ValueError: unconverted data remains'. I'm just trying to figure out what the last part of the date is used for so that I can convert that string to a proper datetime object in python.

Happy Holidays!

Upvotes: 1

Views: 3648

Answers (2)

bakkal
bakkal

Reputation: 55448

Your date seems to be in the ISO 8601 format, I don't think datetime handles the timezone information at the end of the string format.

You can use pip install python-dateutil, its parser can return a datetime object :

import dateutil.parser
datestr = '2012-12-25T08:52:00-05:00'
dateutil.parser.parse(datestr)
>>> datetime.datetime(2012, 12, 25, 8, 52, tzinfo=tzoffset(None, -18000)) 

Upvotes: 5

ThiefMaster
ThiefMaster

Reputation: 318468

The -05:00 indicates the timezone offset from UTC, i.e. %z would be the correct strptime argument to parse it.

If the time is UTC the offset might be indicated using Z, e.g. 2012-12-25T08:52:00Z. Not sure if %z would actually accept this...

Upvotes: 0

Related Questions