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

如何使用Python生成两个给定月份之间的带年份的月份列表

跨指定月份区间的全量带年份月份列表生成实现

原代码的问题定位

  • 原解析格式和实际输入不匹配:代码里写的datetime.strptime用%Y-%m-%d格式串解析,但实际输入的月份是Mar2020这类“3位英文月份缩写+4位年份”的格式,直接运行会触发解析报错
  • 原代码是把整列的df值当单组起止时间处理,没有实现逐行遍历的逻辑,无法匹配批量多行的输入数据

核心实现逻辑

  1. 修正月份解析格式:对应Mar2020这类输入,Python datetime模块的正确解析格式串为"%b%Y"
  2. 采用月度整数序号步进法生成连续序列:把每个月份换算成“从公元1年1月开始的累计月数”,从起始月序号遍历到结束月序号,每步对应一个自然月,避免用timedelta逐天计算时出现的大小月、闰年偏移误差
  3. 把每个序列节点转回为要求的XxxYYYY格式字符串,拼接为逗号分隔的列表

完整可运行代码

首先是通用的月份区间生成函数:

from datetime import datetime
import pandas as pd

def generate_month_span(start_month_str, end_month_str):
    # 解析输入的月份字符串,匹配如"Mar2020"的格式
    start_dt = datetime.strptime(start_month_str, "%b%Y")
    end_dt = datetime.strptime(end_month_str, "%b%Y")

    # 计算累计月数,月份用0起始索引避免12月的计算越界
    start_total = start_dt.year * 12 + (start_dt.month - 1)
    end_total = end_dt.year * 12 + (end_dt.month - 1)

    month_list = []
    for total in range(start_total, end_total + 1):
        year = total // 12
        month = total % 12 + 1
        # 转回要求的字符串格式,如"Mar2020"
        month_str = datetime(year=year, month=month, day=1).strftime("%b%Y")
        month_list.append(month_str)
    
    # 拼接为逗号分隔的字符串
    return ",".join(month_list)

然后是和pandas DataFrame结合的调用代码:

# 构建和你输入匹配的示例DataFrame
df = pd.DataFrame({
    "Month1": ["Mar2020", "Nov2020", "Sep2020", "Jun2020", "Oct2020"],
    "Month2": ["Sep2020", "Jan2021", "Feb2021", "Dec2020", "Mar2021"]
})

# 逐行生成Month_list列
df["Month_list"] = df.apply(
    lambda row: generate_month_span(row["Month1"], row["Month2"]),
    axis=1
)

运行效果说明

  • 生成的Month_list列内容完全匹配给出的期望格式,典型输出示例:
    • Nov2020到Jan2021对应输出Nov2020,Dec2020,Jan2021
    • Sep2020到Feb2021对应输出Sep2020,Oct2020,Nov2020,Dec2020,Jan2021,Feb2021
  • 全流程不需要额外调整字符串格式,生成结果可以直接导出使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 23:24:03