Search code examples
pythonstrptime

Troubleshooting 'ValueError: time data ... does not match format' when using datetime.strptime


My input string is '16-MAR-2010 03:37:04' and i want to store it as datetime.

I am trying to use:

db_inst.HB_Create_Ship_Date = datetime.strptime(fields[7]," %d-%b-%Y %H:%M:%S ") 
fields[7] = '16-MAR-2010 03:37:04' 

I am getting an error:

::ValueError: time data '16-MAR-2010 03:37:04' does not match format ' %d-%b-%Y %H:%M:%S ' 

Solution

  • Edit:
    As John mentions, make it easier on yourself and remove the leading and trailing spaces.

    Another thought:
    Your current locale may not specify "MAR" as a month abbreviation.

    What does the output of this code give?:

    import locale
    locale.getdefaultlocale()
    

    I tested your code on a Linux machine (Ubuntu 9.10, Python 2.6.4) and got the ValueError.
    I removed the spaces, changed to non-English locale (Czech), and got the ValueError.

    Academic note:
    Oddly your code works on Windows XP Python 2.5.5 with the extraneous spaces:

    >>> from datetime import datetime
    >>> dt = '16-MAR-2010 03:37:04'
    >>> datetime.strptime(dt, " %d-%b-%Y %H:%M:%S ")
    datetime.datetime(2010, 3, 16, 3, 37, 4)