0

I can't figure out why this date string throws an error when I try to convert it into a datetime object.

My date string is in the standard ISO-8601 format: u'2013-11-05T20:24:51+0000'

Apparent format based on Python's strptime documentation: '%Y-%m-%dT%H:%M:%S%Z'

But for some reason, when I run:

test = datetime.strptime('2013-11-05T20:24:51+0000', '%Y-%m-%dT%H:%M:%S%Z')

I get

ValueError: time data '2013-11-05T20:24:51+0000' does not match format '%Y-%m-%dT%H:%M:%S%Z'`
Jeff Widman
  • 22,014
  • 12
  • 72
  • 88
  • 1
    If you do that often and dislikes writing strptime expressions as I do, try http://labix.org/python-dateutil – Pedro Werneck Nov 07 '13 at 22:15
  • Yep--definitely a duplicate. When I originally posted the question, I didn't realize it was in ISO 8601 format, so that question wasn't showing up when I searched. Feel free to close/merge or whatever is appropriate here. – Jeff Widman Nov 07 '13 at 22:22

1 Answers1

2

%Z is the wrong directive here.

Try this

datetime.strptime('2013-11-05T20:24:51+0000', '%Y-%m-%dT%H:%M:%S+%f')

More here

Demo:

>>> from datetime import datetime
>>> datetime.strptime('2013-11-05T20:24:51+0000', '%Y-%m-%dT%H:%M:%S%Z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '2013-11-05T20:24:51+0000' does not match format '%Y-%m-%dT%H:%M:%S%Z'
>>> datetime.strptime('2013-11-05T20:24:51+0000', '%Y-%m-%dT%H:%M:%S+%f')
datetime.datetime(2013, 11, 5, 20, 24, 51)
karthikr
  • 97,368
  • 26
  • 197
  • 188