python 转换以下类型的DateTime对象:%B %D %Y

dkqlctbz  于 2023-04-19  发布在  Python
关注(0)|答案(2)|浏览(107)

我有一个日期:

'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](https://stackoverflow.com/questions/18797171/convert-an-integer-number-in-a-date-to-the-month-name-using-python)

b09cbbtk

b09cbbtk1#

使用%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')
dvtswwa3

dvtswwa32#

from datetime import datetime
dates = 'September 17, 2013'
if ',' in date_str:
# Convert the date string to a datetime object
    date_obj = datetime.strptime(date_str, "%B %d, %Y")
        
# Format the date object to the desired format
   formatted_date = date_obj.strftime("%Y/%-m/%-d")

print("Converted date:", formatted_date)

相关问题