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

如何在Python中根据年份和季度获取过去9个月的月末日期

获取指定季度前9个月的每月月末日期(Python实现)

这里有两种实现方式,一种纯依赖标准库,另一种用第三方库简化逻辑,都能满足你的需求:

方法一:纯标准库实现

不需要额外安装依赖,用datetime模块就能搞定:

import datetime

def get_last_day(year: int, month: int) -> datetime.date:
    """获取指定年月的月末日期"""
    # 计算下个月第一天,减1天就是当月最后一天,自动处理闰年2月
    if month == 12:
        next_year = year + 1
        next_month = 1
    else:
        next_year = year
        next_month = month + 1
    next_first = datetime.date(next_year, next_month, 1)
    return next_first - datetime.timedelta(days=1)

def get_past_9_months_last_days(year: int, quarter: str) -> list[str]:
    """输入年份和季度,返回过去9个月的每月月末日期(从近到远排序)"""
    quarter_map = {'Q1': 1, 'Q2': 4, 'Q3': 7, 'Q4': 10}
    if quarter not in quarter_map:
        raise ValueError("季度格式错误,请输入Q1/Q2/Q3/Q4")
    
    start_month = quarter_map[quarter]
    # 基准月份是季度起始月的前一个月(比如Q3的起始月是7月,基准月就是6月)
    current_year, current_month = year, start_month - 1
    if current_month == 0:
        current_year -= 1
        current_month = 12
    
    last_days = []
    for _ in range(9):
        day = get_last_day(current_year, current_month)
        last_days.append(day.strftime('%Y-%m-%d'))
        # 往前推一个月,处理跨年情况
        if current_month == 1:
            current_year -= 1
            current_month = 12
        else:
            current_month -= 1
    
    return last_days

# 测试示例输入
if __name__ == "__main__":
    dates = get_past_9_months_last_days(2022, 'Q3')
    for date_str in dates:
        print(date_str)

运行测试代码后,输出结果为:

2022-06-30
2022-05-31
2022-04-30
2022-03-31
2022-02-28
2022-01-31
2021-12-31
2021-11-30
2021-10-31

方法二:用python-dateutil简化逻辑

如果可以安装第三方库,python-dateutil的relativedelta能自动处理月份推移和月末调整,代码更简洁:

from datetime import date
from dateutil.relativedelta import relativedelta

def get_past_9_months_last_days(year: int, quarter: str) -> list[str]:
    quarter_map = {'Q1': 1, 'Q2': 4, 'Q3': 7, 'Q4': 10}
    if quarter not in quarter_map:
        raise ValueError("季度格式错误,请输入Q1/Q2/Q3/Q4")
    
    start_month = quarter_map[quarter]
    # 基准日期是季度起始日的前一天(即前一个月的月末)
    current_date = date(year, start_month, 1) - relativedelta(days=1)
    
    last_days = []
    for _ in range(9):
        last_days.append(current_date.strftime('%Y-%m-%d'))
        # 自动往前推一个月,保持月末日期(比如31号推到没有31号的月份会自动调整到月末)
        current_date -= relativedelta(months=1)
    
    return last_days

# 测试
if __name__ == "__main__":
    dates = get_past_9_months_last_days(2022, 'Q3')
    for date_str in dates:
        print(date_str)

使用前需要先安装库:

pip install python-dateutil

核心逻辑说明

两种方法的核心思路一致:

  1. 先把季度转换为对应的起始月份(Q1=1,Q2=4,Q3=7,Q4=10)。
  2. 以季度起始月的前一个月月末为起点,连续往前取9个月份的月末日期。
  3. 通过“下个月第一天减1天”或relativedelta自动处理月末日期,避免手动判断每个月的天数和闰年问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:10:47