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

Python将字符串列表转为日期函数报错:AttributeError问题求助

问题排查与解决

错误原因分析

  • 导入与调用冲突:你使用from datetime import datetime导入后,datetime已经直接对应datetime.datetime类,此时再写datetime.datetime会触发属性错误,因为该类本身没有datetime属性。
  • 参数传递错误:将年月日拼接成单个整数传入datetime的方式不符合其构造规则,datetime需要分别接收年、月、日三个独立的整数参数。

修正后的代码

from datetime import datetime 

def make_a_date(values):
    # 将列表中的字符串转为整数,分别赋值给年、月、日
    year, month, day = map(int, values)
    # 构造datetime对象并转为纯日期对象
    return datetime(year, month, day).date()

print(make_a_date(["2022", "11", "8"]))

代码说明

  • map(int, values):批量将输入列表中的字符串元素转换为整数,拆分出年、月、日三个参数。
  • datetime(year, month, day).date():用正确的参数构造datetime实例,再通过date()方法获取仅包含日期部分的对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:40:27