Search code examples
pandasdatetimetimedeltadatetimeindex

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


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.


Solution

  • 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']