%q
格式化程序特定于Period.strftime
,因此必须与Period
个数据一起使用:
该方法识别的指令与标准Python发行版as well as the specific additional directives 101, 102, 103.的time.strftime
函数相同
或者直接创建一个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']