“使用 strptime 函数时,列表索引必须是整数,而不是 str”错误

"list indices must be integers, not str' error when using strptime function

我有一个日期列表,写成字符串,叫做 depart_date

depart_date = ['3/1/2012', '3/4/2012', '3/11/2012']

等等

我想将它们转换为日期对象。这是我的:

for i in depart_date:
    dep_date = datetime.strptime(depart_date[i], '%m/%d/%Y')

它给了我 TypeError: list indices must be integers, not str. 我不确定为什么会收到此错误,因为我认为 strptime 函数应该将字符串转换为日期对象。

有什么帮助吗??

您需要添加.Length

for i in depart_date.Length:
    dep_date = datetime.strptime(depart_date[i], '%m/%d/%Y')

选择:

for i in depart_date:
    dep_date = datetime.strptime(i, '%m/%d/%Y')