[英]Python convert ddmmyy format to valid date
I was trying to convert a date string to a valid date python format, but I got a erroneous date: 我试图将日期字符串转换为有效的日期python格式,但是日期错误:
>from datetime import datetime
>mydate = '300413' # is 2013-04-30
>print datetime.strptime(mydate,'%d%m%Y')
>0413-02-01 00:00:00
How can I parse to a valid date, this date string? 如何解析该日期字符串为有效日期?
As listed in the documentation , %Y
is the code for a four-digit year. 如文档中所列,
%Y
是四位数年份的代码。 You should be using the code for a two-digit year, %y
. 您应该将代码用于两位数年份
%y
。
If you read strptime()
and strftime()
Behavior in the docs, %Y
means: 如果您在文档中阅读了
strptime()
和strftime()
行为 ,则%Y
表示:
Year with century as a decimal number [0001,9999]
以世纪作为十进制数字的年份[0001,9999]
But you're giving it a 2-digit year, with no century. 但是您给它的年份是两位数, 没有世纪。
That's supposed to raise a ValueError
. 那应该引发
ValueError
。 For example, if you try it with 2.5.6, 2.7.2, 3.2.1, or 3.3.0, you get this: 例如,如果您尝试使用2.5.6、2.7.2、3.2.1或3.3.0进行操作,则会得到以下信息:
ValueError: time data '300413' does not match format '%d%m%Y'
ValueError:时间数据“ 300413”与格式“%d%m%Y”不匹配
But, thanks to a bug in older versions of Python, you might get garbage instead. 但是,由于旧版本的Python中的错误,您可能会得到垃圾。
If you want a 2-digit year, use %y
, when means: 如果您想要两位数的年份,请使用
%y
,这意味着:
Year without century as a decimal number [00,99].
没有世纪的年份作为十进制数字[00,99]。
try: 尝试:
print datetime.strptime('300413','%d%m%y')
2013-04-30 00:00:00
only change '%Y'
with '%y'
仅将
'%Y'
更改为'%y'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.