using MonthEnd and Day offsets
这是因为 2022 年 4 月 5 日是before您的月底 (2022-04-30)。
您可以使用:
pd.date_range("2022-01-13", pd.Timestamp("2022-04-05")+pd.offsets.MonthEnd(),
freq='M', inclusive='both')
一个更强大的变体也可以处理输入日期已经是月末的情况:
pd.date_range("2022-01-13",
pd.Timestamp("2022-04-05")-pd.offsets.Day()+pd.offsets.MonthEnd(),
freq='M', inclusive='both')
Output:
DatetimeIndex(['2022-01-31', '2022-02-28', '2022-03-31', '2022-04-30'],
dtype='datetime64[ns]', freq='M')
替代方案:使用Period
pd.date_range(pd.Period('2022-01-13', 'M').to_timestamp(),
pd.Period('2022-04-30', 'M').to_timestamp(how='end'),
freq='M', inclusive='both')
中间体:
pd.Period('2022-01-13', 'M').to_timestamp()
# Timestamp('2022-01-01 00:00:00')
pd.Period('2022-04-30', 'M').to_timestamp(how='end')
# Timestamp('2022-04-30 23:59:59.999999999')
或作为句点:period_range
pd.period_range('2022-01-13', '2022-04-30', freq='M')
Output:
PeriodIndex(['2022-01', '2022-02', '2022-03', '2022-04'], dtype='period[M]')