-2

I need to parse a datetime object from a give date as a string. The date looks like this: 2015-11-21T15:30:00

However, the following fails: datetime.strptime("%Y-%m-%d'T'%H:%M:%S", "2015-11-21T15:30:00") with the following error message:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data "%Y-%m-%d'T'%H:%M:%S" does not match format '2015-11-21T15:30:00'

What am I doing wrong here?

toom
  • 11,026
  • 22
  • 77
  • 119
  • You've put the `T` in quotes - why did you put the `T` in quotes? There are no quotes in the string you're trying to parse. – jonrsharpe Nov 11 '15 at 15:09
  • Afaik this is required if another character appears in a string date. This should be a correct usage - at least from my other experiences. BTW: Removing the quotes does not solve the problem – toom Nov 11 '15 at 15:11
  • your experiences are wrong in this case (notice that all escape sequences start with `%` and therefore you don't need to escape `T`). – jfs Nov 11 '15 at 15:12
  • Your advice does noth work. Or please give me the exact pattern you mean – toom Nov 11 '15 at 15:13
  • 2
    You also have the template and the string to parse against it the wrong way around, which is why the *"time data"* is your format and the *"format"* is your time data. I'd strongly recommend reading the docs, see e.g. https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior – jonrsharpe Nov 11 '15 at 15:14
  • related: [How do I translate a ISO 8601 datetime string into a Python datetime object?](http://stackoverflow.com/q/969285/4279) – jfs Nov 11 '15 at 15:17

1 Answers1

2

The correct format of strptime is (date_string, format). So you were doing it the other way around. Plus, you dont need the ' of the T:

datetime.strptime("2015-11-21T15:30:00", "%Y-%m-%dT%H:%M:%S")
Avión
  • 6,449
  • 6
  • 52
  • 91