python - 如何让 strftime 输出年度季度?

标签 python pandas strftime

我正在尝试用 python 创建一个季度列表;根据文档( https://pandas.pydata.org/docs/reference/api/pandas.Period.strftime.html ), %q (我相信)应该输出日历季度的整数表示,但我得到的输出只是字面上的 %q

输入:

pd.date_range('2021-01-01','2022-01-01',freq='Q').strftime('%Y-%q').tolist()

预期输出:

['2021-01', '2021-02', '2021-03', '2021-04']

实际输出:

['2021-%q', '2021-%q', '2021-%q', '2021-%q']

最佳答案

%q 格式化程序特定于 Period.strftime ,因此它必须与 Period 数据一起使用:

The method recognizes the same directives as the time.strftime function of the standard Python distribution, as well as the specific additional directives %f, %F, %q.

创建一个 period_range直接(但请注意,它包括结束日期,与 date_range 不同):

periods = pd.period_range('2021-01-01', '2022-01-01', freq='Q')
# PeriodIndex(['2021Q1', '2021Q2', '2021Q3', '2021Q4', '2022Q1'], dtype='period[Q-DEC]')

periods.strftime('%Y-0%q').tolist()
# ['2021-01', '2021-02', '2021-03', '2021-04', '2022-01']

或者将现有的 DatetimeIndex 转换为 PeriodIndex :

dates = pd.date_range('2021-01-01', '2022-01-01', freq='Q')
# DatetimeIndex(['2021-03-31', '2021-06-30', '2021-09-30', '2021-12-31'], dtype='datetime64[ns]', freq='Q-DEC')

pd.PeriodIndex(dates).strftime('%Y-0%q').tolist()
# ['2021-01', '2021-02', '2021-03', '2021-04']

关于python - 如何让 strftime 输出年度季度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71385329/

相关文章:

c - 使用 strftime() 获取 utc 时间戳

Python:解析类不打印任何内容?

Python GTK 3+ 控制关闭窗口

Python-单热编码为单列

php - 如何将周数和年份转换为 unix 时间戳?

linux - 如何转换dd/mm/yy hh :mm:ss to yyyy-mm-ddThh:mm:ss using linux?

javascript - 如何从在 Chart.JS 中运行的 PHP 生成 JSON

python - 如何在 Jenkins UI 中执行本地 python 脚本

Pandas 数据框前 ​​x 列

python - Pandas 日期时间索引类型错误