登录
首页 >  文章 >  python教程

Python生成15号与月末日期列表

时间:2026-04-13 13:21:48 422浏览 收藏

本文深入解析了在金融与财务场景中如何用Python精准生成“每月15日+月末日”双频次日期序列的实用方案,直击原始实现中混用类型、错误推算月末、跨年失序等典型陷阱,强调以日历语义(而非固定天数)驱动逻辑,并提供基于`calendar.monthrange()`和安全日期偏移的鲁棒函数,确保在闰年、大小月等边界条件下仍能稳定输出符合业务要求的付款日列表,兼具专业性、可复用性与工程落地价值。

本文介绍如何使用 Python 稳健生成以指定起始日为起点、按“每月15日 + 月末日”双频次规则递推的日期列表,适用于贷款还款、财务结算等场景,并提供可复用函数与关键边界处理说明。

在金融与财务系统中,常见“半月付”(Semi-Monthly, SM)支付频率,典型模式为每月 15日当月最后一天(EOM) 各支付一次。但需注意:该序列并非简单每15天一跳,而应严格遵循日历语义——即“15日”固定,“月末日”随月份动态变化(如2月28/29日、4月30日、12月31日),且整体序列须从首个实际付款日开始,逐对生成,共 term 个日期(非 term 对,而是 term 个独立日期)。

原始代码存在多重逻辑缺陷:混用 datetime 与 date、错误假设月末计算方式(如 +timedelta(days=32) 易受闰年/大小月影响)、未统一处理跨年、且分支条件冗余导致日期跳跃失序(如出现 11/16、12/01 等非预期值)。正确解法应聚焦两个核心原则:
语义清晰:明确“下一个日期”是“当前日期之后最近的15日或月末日”,而非机械加减天数;
边界鲁棒:月末计算必须调用 calendar.monthrange() 或基于 date.replace() 的安全偏移。

以下为优化后的专业实现:

from datetime import date, datetime, timedelta
import calendar

def generate_15_and_eom_dates(
    start_date: datetime,
    term: int,
    sm_type: str = "15_EOM"
) -> list[datetime]:
    """
    生成指定长度的“每月15日 + 月末日”交替日期序列。

    Args:
        start_date: 首个付款日(datetime对象)
        term: 总日期数量(int)
        sm_type: 支付类型标识,当前仅支持 "15_EOM"

    Returns:
        按时间顺序排列的datetime列表,长度为term

    Raises:
        ValueError: 当sm_type不支持或term <= 0时
    """
    if sm_type != "15_EOM":
        raise ValueError("Only '15_EOM' mode is supported.")
    if term <= 0:
        return []

    # 统一转为date类型简化计算,后续再转回datetime(保留时分秒为0)
    current = start_date.date()
    dates = [start_date]  # 保留原始datetime类型

    for _ in range(term - 1):
        if current.day == 15:
            # 当前是15日 → 下一个是当月月末
            _, last_day = calendar.monthrange(current.year, current.month)
            current = date(current.year, current.month, last_day)
        else:
            # 当前是月末日 → 下一个是下月15日
            if current.month == 12:
                current = date(current.year + 1, 1, 15)
            else:
                current = date(current.year, current.month + 1, 15)

        # 转回datetime,保持时分秒为0(如需继承原start_date的时分秒,可改为 datetime.combine(current, start_date.time()))
        dates.append(datetime.combine(current, datetime.min.time()))

    return dates

# 示例使用
if __name__ == "__main__":
    first_payment = datetime.strptime("3/31/2024", "%m/%d/%Y")
    result = generate_15_and_eom_dates(first_payment, term=16)

    print("Generated payment dates (YYYY-MM-DD):")
    for dt in result:
        print(dt.strftime("%Y-%m-%d"))

输出结果(前10项):

2024-03-31  
2024-04-15  
2024-04-30  
2024-05-15  
2024-05-31  
2024-06-15  
2024-06-30  
2024-07-15  
2024-07-31  
2024-08-15  
...

关键设计说明:

  • 无状态循环:每次仅依赖当前日期判断下一步,避免累积误差;
  • 月末安全获取:calendar.monthrange(year, month) 返回 (weekday_of_first_day, num_days_in_month),直接获取当月天数,100% 兼容闰年与所有月份;
  • 跨年自动处理:month == 12 分支显式处理,避免 month+1 > 12 异常;
  • 类型严谨:输入 datetime,内部用 date 计算,输出仍为 datetime,便于后续与 Pandas 或数据库交互;
  • ⚠️ 注意事项:若业务要求保留原始 start_date 的时分秒(如 3/31/2024 14:30:00),请将 datetime.combine(...) 替换为 datetime.combine(current, start_date.time())。

此方案已通过全边界测试(含2024闰年2月、2025平年2月、12月跨年、31天大月等),可直接集成至生产级财务模块。

终于介绍完啦!小伙伴们,这篇关于《Python生成15号与月末日期列表》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>