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

Python如何优雅通用生成回溯两年的连续月份日期元组列表

实现方案

核心逻辑是先锚定当前月份的第一天,从指定回溯年限的最早月份开始,逐月滑动生成「当前月-下一月」的格式化元组,直到覆盖到当前月份为止,全程自动处理跨年、大小月、闰月的边界问题,不需要手动硬编码。


方案1:纯Python标准库实现(无额外依赖)

不需要安装任何第三方包,直接使用Python内置的datetime和calendar模块即可:

from datetime import datetime, timedelta
from calendar import monthrange

def generate_month_pairs(back_years: int = 2) -> list[tuple[str, str]]:
    pairs = []
    # 定位到当前月份的第一天作为游标起点
    cursor = datetime.today().replace(day=1)
    # 先把游标移到N年前的当月第一天
    for _ in range(back_years * 12):
        # 往前跳一个月:减去上月的总天数
        last_day_of_prev_month = cursor - timedelta(days=1)
        cursor = last_day_of_prev_month.replace(day=1)
    
    # 逐月滑动生成相邻月份对,直到覆盖当前月份
    end_threshold = datetime.today().replace(day=1)
    while cursor <= end_threshold:
        # 计算下一个月的第一天
        days_in_curr_month = monthrange(cursor.year, cursor.month)[1]
        next_month = cursor + timedelta(days=days_in_curr_month)
        pairs.append((
            cursor.strftime("%Y-%m"),
            next_month.strftime("%Y-%m")
        ))
        cursor = next_month
    return pairs

# 调用示例
dates = generate_month_pairs(back_years=2)

方案2:基于dateutil的简洁实现(推荐)

如果可以安装轻量第三方依赖,用python-dateutil的relativedelta处理月份偏移可以省去手动计算月份天数、跨年的逻辑,代码可读性更高,几乎不会出边界bug:

  1. 先安装依赖:
    pip install python-dateutil
    
  2. 实现代码:
    from datetime import datetime
    from dateutil.relativedelta import relativedelta
    
    def generate_month_pairs(back_years: int = 2) -> list[tuple[str, str]]:
        pairs = []
        current_month_start = datetime.today().replace(day=1)
        # 定位到N年前的当月起点
        cursor = current_month_start - relativedelta(years=back_years)
        
        while cursor <= current_month_start:
            next_month = cursor + relativedelta(months=1)
            pairs.append((
                cursor.strftime("%Y-%m"),
                next_month.strftime("%Y-%m")
            ))
            cursor = next_month
        return pairs
    
    # 调用示例
    dates = generate_month_pairs(back_years=2)
    

说明

  • 两种方案输出格式完全匹配需要的("from_date", "to_date")字符串元组列表,默认回溯2年,修改back_years参数即可自定义回溯时长。
  • 提供的硬编码列表存在手误,缺失了('2020-10', '2020-11')这一组连续月份对,上述自动生成逻辑会补全所有连续项,不会出现断档。

内容的提问来源于stack exchange,提问作者axox-ea

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 12:39:50