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

如何基于Pandas Timestamp获取下一月/季度/年/半年的期末日期

实现方法

你可以通过「先偏移对应周期时长,再取偏移后所在周期的期末日期」的逻辑实现,不用额外判断输入是否为当期期末,代码如下:

import pandas as pd

def get_next_period_ends(input_ts: pd.Timestamp) -> dict:
    # 下一月期末:偏移1个月后取当月月末
    next_month = input_ts + pd.DateOffset(months=1)
    next_month_end = (next_month + pd.offsets.MonthEnd(0)).strftime('%Y-%m-%d')
    
    # 下一季度期末:偏移3个月后取当季季末
    next_quarter = input_ts + pd.DateOffset(months=3)
    next_quarter_end = (next_quarter + pd.offsets.QuarterEnd(0)).strftime('%Y-%m-%d')
    
    # 下一年期末:偏移1年后取当年年末
    next_year = input_ts + pd.DateOffset(years=1)
    next_year_end = (next_year + pd.offsets.YearEnd(0)).strftime('%Y-%m-%d')
    
    # 下半年期末:偏移6个月后取所在半年的期末(上半年期末6.30,下半年期末12.31)
    next_half = input_ts + pd.DateOffset(months=6)
    half_month = 6 if next_half.month <=6 else 12
    next_biannual_end = (next_half.replace(month=half_month, day=1) + pd.offsets.MonthEnd(0)).strftime('%Y-%m-%d')
    
    return {
        "next_month_end": next_month_end,
        "next_quarter_end": next_quarter_end,
        "next_year_end": next_year_end,
        "next_biannual_end": next_biannual_end
    }

测试验证

用你给出的示例输入测试:

input_ts = pd.Timestamp('1999-12-30')
print(get_next_period_ends(input_ts))

输出结果完全符合预期:

{
    'next_month_end': '2000-01-31',
    'next_quarter_end': '2000-03-31',
    'next_year_end': '2000-12-31',
    'next_biannual_end': '2000-06-30'
}

即使输入本身是当期期末,结果也正确,比如输入pd.Timestamp('1999-12-31'),返回结果和上面完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:24:06