Remove time portion of DateTime index in pandas

You can control your Index object with a simple function like this:

def set_date_range(start_date, number_of_periods, frequency):
            date_range = pd.date_range(start= start_date, periods=number_of_periods, freq=frequency)

            for date in date_range:
                print(date)
            print()

set_date_range('1/1/2018', 5, "MS")

See the line below with the comment, it'll remove the time portion

def set_date_range(start_date, number_of_periods, frequency):
            date_range = pd.date_range(start= start_date, periods=number_of_periods, freq=frequency)

            date_range = date_range.date # ASSIGNING THIS GETS RID OF THE TIME PORTION

            for date in date_range:
                print(date)
            print()

set_date_range('1/1/2018', 5, "MS")

You can maintain the datetime functionality and set the time portion to 00:00:00 with normalize.

df.index = df.index.normalize()

# For non-Index datetime64[ns] dtype columns you use the `.dt` accessor:
# df['column'] = df['column'].dt.normalize()

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4], index=pd.date_range('2018', periods=4, freq='H'))

df.index = df.index.normalize()

print(df)
#            0
#2018-01-01  1
#2018-01-01  2
#2018-01-01  3
#2018-01-01  4

Looking at the index:

df.index
#DatetimeIndex(['2018-01-01', '2018-01-01', '2018-01-01', '2018-01-01'], dtype='datetime64[ns]', freq=None)

And the values are Timestamps:

df.index[0]
#Timestamp('2018-01-01 00:00:00')

With the date attribute:

df.index = df.index.date

Example:

>>> df = pd.DataFrame([1, 2, 3, 4], index=pd.date_range('2018', periods=4, freq='H'))
>>> df.index = df.index.date
>>> df
            0
2018-01-01  1
2018-01-01  2
2018-01-01  3
2018-01-01  4

Note: that this will get you object dtype in Pandas. All attributes are here. It's technically an array of native Python datetime.date objects. See ALollz's answer to keep the dtype datetime-like.

Tags:

Python

Pandas