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

Python函数突发TypeError:datetime缺失必填参数'month'排查与解决

问题分析与修复方案

错误根源

这个错误的核心是传给datetime()的参数数量不足。datetime()构造函数至少需要year、month、day三个位置参数,但你的d.split('-')返回的列表长度不是3,展开后自然缺少必填的month(或其他参数)。

之前运行正常现在报错,本质是目标目录里新增了不符合原有命名规则的文件:原本文件名的stem拆分后,d对应的部分都是yyyy-mm-dd格式,但现在有文件的这部分格式异常(比如变成2024-10、20241001或者多了横杠),导致拆分后元素数量不对。

修复方案

方案1:添加格式校验与异常捕获

在解析日期前先校验格式,同时捕获异常,避免单个坏文件导致整个函数崩溃:

from datetime import datetime
from pathlib import Path

def get_newest(filepath: str) -> dict:
    maxs = {}
    for file in Path(filepath).iterdir():
        if file.is_file():
            try:
                *_, t, d, _ = file.stem.split('_')
                date_parts = d.split('-')
                # 确保拆分后是年、月、日三个部分
                if len(date_parts) != 3:
                    print(f"跳过格式错误的文件:{file.name},日期部分不符合yyyy-mm-dd格式")
                    continue
                d = datetime(*map(int, date_parts))
                maxs[t] = file if t not in maxs else max(file, maxs[t])
            except (ValueError, TypeError) as e:
                print(f"处理文件{file.name}时出错:{str(e)},已跳过")
                continue
    return maxs

方案2:用strptime明确指定日期格式(更健壮)

相比拆分字符串,strptime可以直接指定预期的日期格式,解析失败时能更精准地定位问题:

from datetime import datetime
from pathlib import Path

def get_newest(filepath: str) -> dict:
    maxs = {}
    for file in Path(filepath).iterdir():
        if file.is_file():
            try:
                *_, t, d_str, _ = file.stem.split('_')
                # 明确指定日期格式为yyyy-mm-dd
                d = datetime.strptime(d_str, "%Y-%m-%d")
                maxs[t] = file if t not in maxs else max(file, maxs[t])
            except (ValueError, TypeError) as e:
                print(f"处理文件{file.name}时出错:{str(e)},已跳过")
                continue
    return maxs

额外建议

  1. 先去目标目录排查新增文件,找出命名不符合规则的文件,要么清理要么统一格式;
  2. 如果文件名规则有变动,需要同步调整file.stem.split('_')的拆分逻辑,确保t和d的位置正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:12:51