Cannot parse the date in Python

2019-01-20 16:39发布

问题:

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?

回答1:

%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.


回答2:

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



回答3:

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')