我的日期为:
'September 17, 2013'
我想将其转换为:
2013-09-17
我尝试了这个来自这个stackoverflow问题的提示[1]:
mydate = datetime.datetime.strptime("September 17, 2013", '%B %d, %y')
但它给了我一个:
File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 13
我该怎么办?
[1] convert an integer number in a date to the month name using python
答案 0 :(得分:2)
使用%Y
代替%y
。后者只匹配2位数
%y Year without century as a zero-padded decimal number. 00, 01, ..., 99
%Y Year with century as a decimal number. 1970, 1988, 2001, 2013
演示:
>>> import datetime
>>> datetime.datetime.strptime("September 17, 2013", '%B %d, %y')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 13
>>> x = datetime.datetime.strptime("September 17, 2013", '%B %d, %Y')
>>> x
datetime.datetime(2013, 9, 17, 0, 0)
>>>
然后,
x.strftime('%Y-%m-%d')