Home > Back-end >  Round all index to 30 min in Pandas datetimeindex
Round all index to 30 min in Pandas datetimeindex

Time:12-30

I know about round, ceil, floor functions.

df.index.round("30min")

This rounds to the nearest 30 minute interval. What I want is that each is rounded to 30 minutes.

In the case of .round 10:15 will be rounded to 10:30 and 10:45 to 11:00. I would want both rounded to 10:30.

The datetime Index:

DatetimeIndex(['2021-11-29 09:30:00', '2021-11-29 09:45:00',
               '2021-11-29 10:00:00', '2021-11-29 10:15:00',
               '2021-11-29 10:30:00', '2021-11-29 10:45:00',
               '2021-11-29 11:00:00', '2021-11-29 11:15:00',
               '2021-11-29 11:30:00', '2021-11-29 11:45:00',
               ...
               '2021-12-27 13:30:00', '2021-12-27 13:45:00',
               '2021-12-27 14:00:00', '2021-12-27 14:15:00',
               '2021-12-27 14:30:00', '2021-12-27 14:45:00',
               '2021-12-27 15:00:00', '2021-12-27 15:15:00',
               '2021-12-27 15:30:00', '2021-12-27 15:45:00'],
              dtype='datetime64[ns]', name='Datetime', length=520, freq=None)

CodePudding user response:

Use DatetimeIndex.floor by hour and add 30 minutes:

df = pd.DataFrame(index=pd.DatetimeIndex(
               ['2021-11-29 09:30:00', '2021-11-29 09:45:00',
               '2021-11-29 10:00:00', '2021-11-29 10:15:00',
               '2021-11-29 10:30:00', '2021-11-29 10:45:00',
               '2021-11-29 11:00:00', '2021-11-29 11:15:00',
               '2021-11-29 11:30:00', '2021-11-29 11:45:00',
               '2021-12-27 13:30:00', '2021-12-27 13:45:00',
               '2021-12-27 14:00:00', '2021-12-27 14:15:00',
               '2021-12-27 14:30:00', '2021-12-27 14:45:00',
               '2021-12-27 15:00:00', '2021-12-27 15:15:00',
               '2021-12-27 15:30:00', '2021-12-27 15:45:00']))

print (df.index.floor("1H")   pd.Timedelta('30min'))

DatetimeIndex(['2021-11-29 09:30:00', '2021-11-29 09:30:00',
               '2021-11-29 10:30:00', '2021-11-29 10:30:00',
               '2021-11-29 10:30:00', '2021-11-29 10:30:00',
               '2021-11-29 11:30:00', '2021-11-29 11:30:00',
               '2021-11-29 11:30:00', '2021-11-29 11:30:00',
               '2021-12-27 13:30:00', '2021-12-27 13:30:00',
               '2021-12-27 14:30:00', '2021-12-27 14:30:00',
               '2021-12-27 14:30:00', '2021-12-27 14:30:00',
               '2021-12-27 15:30:00', '2021-12-27 15:30:00',
               '2021-12-27 15:30:00', '2021-12-27 15:30:00'],
              dtype='datetime64[ns]', freq=None)
  • Related