Home > OS >  shifting a pandas datetime index
shifting a pandas datetime index

Time:03-28

This is a really stupid question, I am guessing, but anyway, here goes:

I have a dataframe with a datetime index which looks like this:

DatetimeIndex(['1995-01-02', '1995-01-03', '1995-01-04', '1995-01-05',
               '1995-01-06', '1995-01-09', '1995-01-10', '1995-01-11',
                '1995-01-12', '1995-01-13'])

Not too surprisingly, the time field is "00:00:00":

bets.index.map(pd.datetime.time)

gives:

 Index([00:00:00, 00:00:00, 00:00:00, 00:00:00, 00:00:00, 00:00:00, 00:00:00,
       00:00:00, 00:00:00, 00:00:00])

I would like to set the time field to something else (e.g., noon), for all the index elements. What is the simplest way to do this?

CodePudding user response:

IIUC, you could use to_timedelta and pass in the required number of hours:

bets.index  = pd.to_timedelta('12h')

Output:

DatetimeIndex(['1995-01-02 12:00:00', '1995-01-03 12:00:00',
               '1995-01-04 12:00:00', '1995-01-05 12:00:00',
               '1995-01-06 12:00:00', '1995-01-09 12:00:00',
               '1995-01-10 12:00:00', '1995-01-11 12:00:00',
               '1995-01-12 12:00:00', '1995-01-13 12:00:00'],
              dtype='datetime64[ns]', freq=None)
  • Related