[英]Converting string to date python
I'm following the following guide on how to convert a string into a date object in python but I came across an error that I don't quite understand. 我正在遵循以下有关如何在python中将字符串转换为日期对象的指南,但是遇到了一个我不太了解的错误。
I'm trying to do the following: 我正在尝试执行以下操作:
buildDateArray.append(dt.strptime(date,"%y-%b-%d %H:%M:%S"))
But I get the bellow error: 但是我得到了下面的错误:
buildDateArray.append(dt.strptime(date,"%y-%b-%d %H:%M:%S"))
File "/usr/lib64/python2.6/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '2014-11-17 00:00:00' does not match format '%y-%b-%d %H:%M:%S'
I don't understand why '2014-11-17 00:00:00' does not match format '%y-%b-%d %H:%M:%S' 我不明白为什么'2014-11-17 00:00:00'与格式'%y-%b-%d%H:%M:%S'不匹配
Can you see what the error is? 您能看到错误是什么吗?
Your format has two problems: 您的格式有两个问题:
%y
matches a two digit year, but your year contains 4. Use %Y
(capital Y
) instead. %y
匹配两位数的年份,但您的年份包含4。请改用%Y
(大写的Y
)。
%b
matches a named month, abbreviated; %b
与指定的月份匹配,缩写; use %m
instead to match a numeric month; 使用
%m
代替数字月份; you need to match 11
here, not Nov
. 您需要在这里匹配
11
,而不是Nov
。
Demo: 演示:
>>> from datetime import datetime
>>> datetime.strptime('2014-11-17 00:00:00', '%Y-%m-%d %H:%M:%S')
datetime.datetime(2014, 11, 17, 0, 0)
When you face a problem like this, try to narrow it down to the components; 当您遇到这样的问题时,请尝试将其范围缩小到各个组件。 you could have tried just the year part for example, and it'd have failed still, but with a different error giving you a big hint as to why it might be failing:
你可以尝试只是举例年份部分,它会失败依然,但使用不同的错误给你一个很大的提示,为什么它可能是失败的:
>>> datetime.strptime('2014', '%y')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 14
Since you are using the datetime.strptime()
class method , you need to look a the correct documentation, found at strftime()
and strptime()
Behavior ; 由于您使用的是
datetime.strptime()
类方法 ,因此需要查看正确的文档,该文档位于strftime()
和strptime()
。 it details what each pattern matches. 它详细说明了每种模式匹配的内容。
You have two problems with your format 您的格式有两个问题
Y
to match the four digit year instead of the lower case y
(it matches only two digit) Y
来匹配四位数的年份,而不是小写的y
(它仅匹配两位数) %m
instead of %b
to match the numeric month instead of the abbreviated month (ie. 11
vs Nov
) %m
而不是%b
来匹配数字月份而不是缩写月份(即11
vs Nov
) Your final format would be: 您的最终格式为:
"%Y-%m-%d %H:%M:%S"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.