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

生日追踪器跨年度日期比较Bug:如何判断日期是否在三周内?

解决生日追踪器跨年度日期比较异常问题

问题根源

原is_first_date_later函数仅通过月日的数值大小判断先后,完全没考虑跨年场景:当today_plus_3weeks处于12月时,任何1月的生日都会被判定为“早于12月”,导致程序持续将1月生日加入upcoming_birthdays,直至清空people列表触发IndexError。

解决方案

我们需要结合当前年份处理生日的日期比较,同时给循环加上非空判断避免索引错误。

1. 替换日期比较逻辑

新增一个专门判断生日是否在指定范围内的函数:

def is_birthday_within_range(birth_date, today, end_date):
    # 将生日转换为当年的日期
    this_year_birth = today.replace(month=birth_date.month, day=birth_date.day)
    if this_year_birth < today:
        # 今年生日已过,视为明年的生日
        this_year_birth = this_year_birth.replace(year=this_year_birth.year + 1)
    # 判断转换后的生日是否不晚于结束日期
    return this_year_birth <= end_date

2. 修改原筛选逻辑

更新upcoming_birthdays的筛选循环,加入列表非空判断,并使用新函数:

today_plus_3weeks = today + d.timedelta(days=21)

# 筛选今日生日(加入非空判断避免索引错误)
while people and people[0].birthdate.month == today.month and people[0].birthdate.day == today.day:
    birthdays_today.append(people.pop(0))

# 筛选未来三周内的生日
while people and is_birthday_within_range(people[0].birthdate, today, today_plus_3weeks):
    upcoming_birthdays.append(people.pop(0))

逻辑说明

  • 把生日转换为当年的具体日期,如果该日期早于今天,自动视为明年的生日(匹配列表按“即将到来的生日”排序的逻辑)。
  • 直接和带年份的today_plus_3weeks比较,彻底解决跨年度的日期判断问题。
  • 循环前先检查people列表是否为空,从根源避免IndexError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:06:31