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

获取datetime日期月份报错:'NoneType' object has no attribute 'month'

解决AttributeError: 'NoneType' object has no attribute 'month'问题

这个错误本质很简单:你的actividad.fecha_real_ini或者actividad.fecha_real_fin其中一个(甚至两个)是None——也就是没有被赋值为有效的datetime对象,自然没法调用.month属性。

我给你两个层面的解决方案:

1. 先做非空检查,避免报错

最直接的是先确认这两个日期变量都有值,再执行循环逻辑:

# 先校验日期是否存在
if actividad.fecha_real_ini is not None and actividad.fecha_real_fin is not None:
    i_real = actividad.fecha_real_ini.month - 1
    while i_real <= actividad.fecha_real_fin.month - 1:
        meses_real[i_real] = True
        i_real += 1
else:
    # 根据你的业务场景处理空值情况,比如打印提示、记录日志或者跳过
    print("提示:fecha_real_ini 或 fecha_real_fin 未设置值,无法执行月份标记")

2. 处理跨年份的边界情况(可选)

如果你的业务中存在起始日期和结束日期跨年份的情况(比如12月到次年2月),原来的循环逻辑会失效(因为11>1,循环根本不会跑)。这时候需要调整逻辑,结合年份来判断:

if actividad.fecha_real_ini is not None and actividad.fecha_real_fin is not None:
    start_year, start_month = actividad.fecha_real_ini.year, actividad.fecha_real_ini.month
    end_year, end_month = actividad.fecha_real_fin.year, actividad.fecha_real_fin.month
    
    current_year, current_month = start_year, start_month
    while (current_year, current_month) <= (end_year, end_month):
        # 转换成0-11的索引
        month_idx = current_month - 1
        meses_real[month_idx] = True
        
        # 切换到下一个月,处理跨年
        current_month += 1
        if current_month > 12:
            current_month = 1
            current_year += 1
else:
    print("提示:日期为空,无法进行月份处理")

内容的提问来源于stack exchange,提问作者Palomita Yañez Quiroz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:39:07