1

My pandas dataframe has DatetimeIndex: DatetimeIndex(['1950-02-07', '1951-12-30, '1952-03-04',..............'2020-04-07'], dtype='datetime64[ns]', length=589, freq=None))

I would like to shift the index by using timedelta by days=-4 in no-leap 365 calenday for example: '1952-03-04' timedelta(days=-4 ) I would like to get '1952-02-28' instead of '1952-02-29'

Could anyone give me some suggestions?

Thank you so much in advance.

linyenheng
  • 33
  • 3

1 Answers1

1

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

I think not.

Can datetime.timedelta skip Feb 29th?

I think not.

One possible solution is test this date and in condition change timedelta by subtract day:

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']
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 1
    Thank you, Jezrael. This is useful. It is better than my ideas that are to duplicate Feb-28th to Feb-29 or to convert pandas Dataframe to xarray DataArray and then use cftime. – linyenheng Oct 22 '20 at 18:52