Search code examples
pythondatetimestrptime

Converting string to date python


I'm following the following guide on how to convert a string into a date object in python but I came across an error that I don't quite understand.

I'm trying to do the following:

buildDateArray.append(dt.strptime(date,"%y-%b-%d %H:%M:%S"))

But I get the bellow error:

    buildDateArray.append(dt.strptime(date,"%y-%b-%d %H:%M:%S"))
  File "/usr/lib64/python2.6/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '2014-11-17 00:00:00' does not match format '%y-%b-%d %H:%M:%S'

I don't understand why '2014-11-17 00:00:00' does not match format '%y-%b-%d %H:%M:%S'

Can you see what the error is?


Solution

  • Your format has two problems:

    • %y matches a two digit year, but your year contains 4. Use %Y (capital Y) instead.

    • %b matches a named month, abbreviated; use %m instead to match a numeric month; you need to match 11 here, not Nov.

    Demo:

    >>> from datetime import datetime
    >>> datetime.strptime('2014-11-17 00:00:00', '%Y-%m-%d %H:%M:%S')
    datetime.datetime(2014, 11, 17, 0, 0)
    

    When you face a problem like this, try to narrow it down to the components; you could have tried just the year part for example, and it'd have failed still, but with a different error giving you a big hint as to why it might be failing:

    >>> datetime.strptime('2014', '%y')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/_strptime.py", line 328, in _strptime
        data_string[found.end():])
    ValueError: unconverted data remains: 14
    

    Since you are using the datetime.strptime() class method, you need to look a the correct documentation, found at strftime() and strptime() Behavior; it details what each pattern matches.