0

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You have two problems with your format

  • Use a capital Y to match the four digit year instead of the lower case y (it matches only two digit)
  • Use %m instead of %b to match the numeric month instead of the abbreviated month (ie. 11 vs Nov)

Your final format would be:

"%Y-%m-%d %H:%M:%S"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.