1

I need to parse date and time. Here is what I've got:

import time
a = time.strptime('Apr 28 2013 23:01', "%b %d %y %H:%M")
print a 

But it gives me

Traceback (most recent call last):
  File "/home/aaa/Documents/python_test.py", line 17, in <module>
    a = time.strptime('Apr 28 2013 23:01', "%b %d %y %H:%M")
  File "/usr/lib/python2.7/_strptime.py", line 467, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'Apr 28 2013 23:01' does not match format '%b %d %y %H:%M'

What am I doing wrong?

3 Answers 3

11

%y should be %Y for a 4 digit year...

From the docs:

%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.
Sign up to request clarification or add additional context in comments.

Comments

0

You can

import time
a = time.strptime('Apr 28 2013 23:01', "%b %d %Y %H:%M")
print time.strftime("%d/%m/%Y",a)

with Y. It is followed by a conversion line of code, and gives result

28/04/2013

Comments

-2

Jon's answer is of course correct, but as you noticed these things can be difficult to find.

As a general suggestion for debugging strptime problems I recommend printing out a known datetime using the format string you use for parsing:

from datetime import datetime

d = datetime(2013, 4, 28, 23, 1)
print d.strftime("%b %d %y %H:%M")
print 'Apr 28 2013 23:01'

A visual comparison of the output lines:

Apr 28 13 23:01
Apr 28 2013 23:01

quickly finds the problem and also works when your format string is correct, but you are working with a different locale (e.g. in Spanish where it would expect 'Abr' instead of 'Apr')

1 Comment

I am not sure what you mean by that. I do not see 'April' in your code and the output from the print statements does not include '4' either.

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.