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

如何将01Q1格式的年份季度字符串转换为Python中的datetime对象

Python 两位年份+季度字符串转datetime对象方法

方法1:纯datetime手动实现(无第三方依赖)

  • 实现逻辑:拆分字符串得到两位年份和季度数值,补全为4位年份后按季度换算对应月份,直接生成datetime对象,默认取季度首日,可自行调整为末日。
from datetime import datetime

def quarter_str_to_datetime(q_str: str) -> datetime:
    year_suffix, quarter_num = q_str.split("Q")
    # 若存在19xx的年份场景,可加判断逻辑调整前缀,此处默认统一为20xx
    full_year = 2000 + int(year_suffix)
    # 季度对应首月:Q1=1月、Q2=4月、Q3=7月、Q4=10月
    start_month = (int(quarter_num) - 1) * 3 + 1
    return datetime(full_year, start_month, 1)

# 测试调用
print(quarter_str_to_datetime("01Q1"))
# 输出:2001-01-01 00:00:00

方法2:用pandas内置格式解析(更便捷)

pandas原生支持季度格式%q,无需手动换算月份,一行即可完成转换。

import pandas as pd

def quarter_str_to_datetime(q_str: str) -> datetime:
    # %y匹配两位年份,%q匹配季度,to_pydatetime()转为原生datetime对象
    return pd.to_datetime(q_str, format="%yQ%q").to_pydatetime()

# 测试调用
print(quarter_str_to_datetime("01Q1"))
# 输出:2001-01-01 00:00:00

如果需要获取季度最后一天的datetime对象,可以修改pandas处理逻辑为:

pd.to_datetime(q_str, format="%yQ%q") + pd.offsets.QuarterEnd(0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:57:01