Cannot parse the date in Python

回眸只為那壹抹淺笑 提交于 2019-11-28 14:20:27
Jon Clements

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!