Rahul99
Rahul99

Reputation: 85

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 ' 

Upvotes: 1

Views: 12748

Answers (4)

mechanical_meat
mechanical_meat

Reputation: 169494

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)

Upvotes: 4

John Machin
John Machin

Reputation: 83022

Lose the spaces at the front and back of your format. I thought that strptime was documented to vary depending on the whims of whoever wrote the C runtime for your box. However it seems I'm wrong. Which would mean that there's a bug in Python.

Python 2.6.4 on Windows doesn't like leading trailing spaces; see below.

*x users, what do you find?

In the meantime, use the lowest common denominator -- lose the spaces. You may also have a locale problem, as Adam mentioned.

With spaces:

>>> datetime.datetime.strptime('16-MAR-2010 03:37:04'," %d-%b-%Y %H:%M:%S ")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\python26\lib\_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '16-MAR-2010 03:37:04' does not match format ' %d-%b-%Y %H
:%M:%S '

Without spaces:

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

Upvotes: 2

Kyle Rosendo
Kyle Rosendo

Reputation: 25287

Try this:

db_inst.HB_Create_Ship_Date = datetime.strptime(fields[7],"%d-%b-%Y %H:%M:%S")

Also, have a look here as a reference for DateTime formatting in Python.

Upvotes: 0

Will
Will

Reputation: 5537

Your format string has a leading space and a trailing space, but your input string does not. Remove the space after the starting quotation mark and before the ending quotation mark.

Upvotes: 2

Related Questions