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

如何将年月格式'202112'转换为下一季度年季度格式'2022Q1'

年月转下一季度(yearqtr格式)实现方案

你的代码没得到预期结果的原因是:pd.to_datetime('202112')会默认解析成2021-12-01,转成季度周期后得到的是当前日期所在的2021Q4,但你需要的是下一季度的结果。下面是两种直接可行的实现方式:

方式一:基于Period对象直接处理

先把字符串转为年月周期的Period,偏移一个季度后格式化输出:

import pandas as pd

# 转为年月周期的Period
month_period = pd.Period('202112', freq='M')
# 偏移一个季度,获取下一季度的Period对象
next_quarter = month_period + pd.offsets.QuarterBegin(startingMonth=1)
# 格式化为所需的'YYYYQN'字符串
output = next_quarter.strftime('%YQ%q')
print(output)  # 输出: 2022Q1

方式二:通过Timestamp偏移转换

先解析为日期,偏移到下一季度起始,再转为季度周期格式:

import pandas as pd

# 按指定格式解析日期,避免自动解析歧义
date = pd.to_datetime('202112', format='%Y%m')
# 偏移到下一季度的第一天
next_qtr_start = date + pd.offsets.QuarterBegin(1, startingMonth=1)
# 转为季度周期并格式化
output = next_qtr_start.to_period('Q').strftime('%YQ%q')
print(output)  # 输出: 2022Q1

重要细节

  • startingMonth=1是确保季度以1月为起始(Q1=1-3月,Q2=4-6月…),如果你的业务中季度起始月份不同,修改这个参数即可。
  • %q是格式化字符,会输出1-4的季度编号,刚好匹配你需要的格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:48:08