views:

303

answers:

4

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 ' 

I am running Python version --EDIT-ME-- on the --EDIT-ME-- operating system.

My locale is --EDIT-ME--.

Which format do I have to use?

+2  A: 

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)
>>>
John Machin
+2  A: 

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.

Will
A: 

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.

Kyle Rozendo
+1  A: 

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)
Adam Bernier
The docs for the locale module mentions """ABMON_1 ... ABMON_12 Return abbreviated name of the n-th month""" but these (and other useful things) don't seem to exist. Any clues?
John Machin
@John: worked with the leading and trailing spaces on WinXP Python version 2.5. Just tried on Ubuntu (Python 2.6.4) and got the ValueError.
Adam Bernier
Just tried on WHAT version of Python on WHICH manifestation of *nix?
John Machin