我们可以将 pandas.DatetimeIndex 的日历指定为 'noleap' 吗?或者可以 datetime.timedelta 跳过 2 月 29 日

Can we assign the calendar of pandas.DatetimeIndex as 'noleap' ? or Can datetime.timedelta skip Feb 29th

我的 pandas 数据框有 DatetimeIndex: DatetimeIndex(['1950-02-07', '1951-12-30, '1952-03-04',......'2020-04-07'], dtype ='datetime64[ns]', 长度=589, 频率=None))

我想在 365 无闰日中使用 timedelta 按 days=-4 移动索引 例如: '1952-03-04' timedelta(days=-4 ) 我想得到 '1952-02-28' 而不是 '1952-02-29'

谁能给我一些建议?

在此先感谢您。

Can we assign the calendar of pandas.DatetimeIndex as 'noleap' ?

我认为不是。

Can datetime.timedelta skip Feb 29th?

我认为不是。

一个可能的解决方案是测试这个日期并在减去天的情况下改变时间增量:

a = ['1952-03-04', '1951-12-30']
idx = pd.to_datetime(a)
print (idx)
DatetimeIndex(['1952-03-04', '1951-12-30'], dtype='datetime64[ns]', freq=None)

out = idx - pd.Timedelta(4, unit='days')
print (out)
DatetimeIndex(['1952-02-29', '1951-12-26'], dtype='datetime64[ns]', freq=None)

out = np.where((out.day == 29) & (out.month == 2), out - pd.Timedelta(1, unit='days'), out)
print (out)
['1952-02-28T00:00:00.000000000' '1951-12-26T00:00:00.000000000']