Cannot Parse The Date In Python
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 las
Solution 1:
%y
should be %Y
for a 4 digit year...
From the docs:
%y Yearwithout century as a decimal number [00,99].
%Y Yearwith century as a decimal number.
Solution 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
Solution 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:
Apr281323:01Apr282013 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')
Post a Comment for "Cannot Parse The Date In Python"