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

如何用Python创建包含月起止日期的Pandas DataFrame

生成指定日期区间的月度DataFrame解决方案

完整实现代码

import pandas as pd
from pandas.tseries.offsets import MonthEnd

start_date = "2020-05-17"
end_date = "2020-07-23"

# 转换为Timestamp对象,简化日期运算
start_ts = pd.Timestamp(start_date)
end_ts = pd.Timestamp(end_date)

# 生成区间内所有月份的第一天序列(freq='MS'表示每月起始日)
month_starts = pd.date_range(start=start_ts.replace(day=1), end=end_ts, freq='MS')

data = []
for month_start in month_starts:
    # 确定当前行的起始日期:首月用给定的start_date,其余用当月第一天
    current_start = start_ts if month_start == start_ts.replace(day=1) else month_start
    # 确定当前行的结束日期:末月用给定的end_date,其余用当月月末
    current_end = end_ts if month_start.month == end_ts.month else (month_start + MonthEnd(1))
    # 提取月份名称和年份
    month_name = month_start.strftime('%B')
    year = month_start.year
    # 组装数据
    data.append({
        'start': current_start.strftime('%Y-%m-%d'),
        'end': current_end.strftime('%Y-%m-%d'),
        'month': month_name,
        'year': year
    })

# 转为DataFrame
df = pd.DataFrame(data)
print(df)

关键步骤说明

  • 日期类型转换:将字符串日期转为pd.Timestamp,便于进行月份替换、加减等运算。
  • 生成月度起始序列:通过pd.date_range的freq='MS'参数,快速生成区间内所有月份的第一天,避免手动遍历日期。
  • 动态处理首尾月:
    • 首月的起始日期保留用户给定的start_date,而非当月第一天;
    • 末月的结束日期保留用户给定的end_date,而非当月月末。
  • 提取月份名称:使用strftime('%B')获取英文全称月份名(若需中文可改用'%b'或其他本地化格式)。

运行代码后将得到预期输出:

start       end         month   year
0  2020-05-17  2020-05-31    May  2020
1  2020-06-01  2020-06-30   June  2020
2  2020-07-01  2020-07-23   July  2020

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:37:54