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

Python不使用date/calendar库实现日期加减 闰年逻辑错误排查

问题根因

代码的问题出在两处核心逻辑错误:

  • leap_year闰年判断逻辑完全错误:使用了除法/而非取余%做整除判断,且判断规则不符合闰年定义,导致无法正确识别2020是闰年,返回2月天数为28天,全年天数计算少了1天
  • 月份天数字典仅初始化一次:mon_max在函数开头基于初始传入年份计算了2月天数,后续循环跨年到其他年份时,没有更新对应新年份的2月天数,导致跨年后的2月天数永远和初始年份一致
修复代码
def leap_year(year):
    # 正确闰年判断规则:能被4整除但不能被100整除,或能被400整除为闰年
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return 29
    return 28

def before(today, num):
    if len(today) != 10:
        return '00-00-0000'
    str_day, str_month, str_year = today.split('-')
    year = int(str_year)
    month = int(str_month)
    day = int(str_day)
    num = int(num)
    mon_max = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}

    while num < 0:
        # 每次循环先更新当前年份的2月天数
        mon_max[2] = leap_year(year)
        tmp_day = day - 1
        if tmp_day < 1:
            tmp_month = month - 1               
            if tmp_month < 1:
                to_month = 12 
                year = year - 1
                to_day = mon_max[to_month]           
            else:
                to_day = mon_max[tmp_month]
                to_month = tmp_month                 
        else:
            to_day = tmp_day
            to_month = month  
        num += 1
        day = to_day
        month = to_month

    next_date = f"{str(to_day).zfill(2)}-{str(to_month).zfill(2)}-{str(year)}"
    return next_date

# 测试案例
print(before("01-01-2021", -366)) # 输出 01-01-2020 符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:45:03