Reputation: 85
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
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
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
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
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