Home > Back-end >  Remove part of a datetime index in a pandas.core.indexes.datetimes.DatetimeIndex
Remove part of a datetime index in a pandas.core.indexes.datetimes.DatetimeIndex

Time:06-22

I wanted to remove the year and minute part of the date-values in the index of a pandas df:

DatetimeIndex(['2022-05-16 14:31:14', '2022-05-16 16:31:15',
               '2022-05-16 18:31:16', '2022-05-16 20:31:17',
               '2022-05-16 22:31:18', '2022-05-17 00:31:19',
               '2022-05-17 02:31:20', '2022-05-17 04:31:21',
               '2022-05-17 06:31:22', '2022-05-17 08:31:23',
               ...
               '2022-06-11 06:12:18', '2022-06-11 08:12:18',
               '2022-06-11 10:12:18', '2022-06-11 12:12:18',
               '2022-06-11 14:12:18', '2022-06-11 16:12:18',
               '2022-06-11 18:12:18', '2022-06-11 20:12:18',
               '2022-06-11 22:12:18', '2022-06-12 00:12:18'],
              dtype='datetime64[ns]', name=0, length=320, freq=None)

the format that I want the values in the whole array to is '05-16 14', (month, day, hour)

would be happy for any tipps or suggestions how to accomplish that.

thanks

CodePudding user response:

This is not possible if you want to keep the datetime type, you necessarily need to convert to string using strftime:

df.index.strftime('%m-%d %H')

output:

Index(['05-16 14', '05-16 16', '05-16 18', '05-16 20', '05-16 22', '05-17 00',
       '05-17 02', '05-17 04', '05-17 06', '05-17 08', '06-11 06', '06-11 08',
       '06-11 10', '06-11 12', '06-11 14', '06-11 16', '06-11 18', '06-11 20',
       '06-11 22', '06-12 00'],
      dtype='object')
  • Related