You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将列表元素转为%m/%d时间格式?Python代码报错求助

解决时间格式转换的ValueError问题

错误原因

你遇到的ValueError: unconverted data remains: 425是因为日期解析格式符不匹配:

  • 你使用了%y%m%d,其中%y代表两位年份(比如22对应2022)
  • 但你的数据是四位年份(比如2022),解析时%y仅匹配前两位20,剩余的220425无法被处理,因此触发报错。

修正后的代码

将datetime.strptime(a, '%y%m%d')中的格式符替换为%Y%m%d(%Y对应四位年份)即可解决问题:

from openpyxl import load_workbook
from datetime import datetime

wb = load_workbook("Book1.xlsx")
ws = wb['Sheet1'] 
column = ws['D']
column_list = [column[x].value for x in range(len(column))]
my_list = column_list[2:]

list_1 = [x[0:8] for x in my_list]
list_2 = []
for a in list_1:
    # 把%y改成%Y,匹配四位年份格式
    date = datetime.strptime(a, '%Y%m%d').strftime('%m/%d')
    list_2.append(date)
print(list_2)

运行结果

执行修正后的代码,会输出你期望的格式:

['04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/25', '04/26', '04/26', '04/26']

内容的提问来源于stack exchange,提问作者Student wahaha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 19:00:25