5

我有一个日期:

'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]使用python将日期中的整数转换为月份名称

4

1 回答 1

4

使用%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')
于 2013-09-21T16:03:14.917 回答