为什么日期与格式不匹配?
>>> import datetime
>>> dt1 = "9/1/2014 0:00"
>>> datetime.datetime.strptime(dt1, "%m/%d/%y %H:%M")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '9/1/2014 0:00' does not match format '%m/%d/%y %H:%M'
这一个要么:
>>> datetime.datetime.strptime(dt1, "%d/%m/%y %H:%M")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '9/1/2014 0:00' does not match format '%d/%m/%y %H:%M'
答案 0 :(得分:1)
让我们打开http://strftime.org/并检查:
%m Month as a zero-padded decimal number.
因此需要09
,而不是9
%d Day of the month as a zero-padded decimal number.
因此需要01
,而不是1
%y Year without century as a zero-padded decimal number.
因此需要14
,而不是2014
%H Hour (24-hour clock) as a zero-padded decimal number.
所以需要00
,而不是0
。
答案 1 :(得分:1)
正确的语法是,
>>> from datetime import datetime
>>> datetime.strptime('2012-09-1 0:00', '%Y-%m-%d %H:%M')
datetime.datetime(2012, 9, 1, 0, 0)
>>>