Python Pandas - Convert times to midnight in DateTimeIndex



To convert times to midnight in DateTimeIndex, use the DateTimeIndex.normalize() in Pandas.

At first, import the required libraries −

import pandas as pd

Create a DatetimeIndex with period 7 and frequency as H i.e. hours −

datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='10H')

Display DateTimeIndex −

print("DateTimeIndex...\n", datetimeindex)

The time component of the date-time is converted to midnight i.e. 00:00:00 −

print("\nNormalize (converted the time component to midnight)...\n",
datetimeindex.normalize())

Example

Following is the code −

import pandas as pd

# DatetimeIndex with period 7 and frequency as H i.e. hours
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='10H')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)

# The time component of the date-time is converted to midnight i.e. 00:00:00
print("\nNormalize (converted the time component to midnight)...\n",
datetimeindex.normalize())

Output

This will produce the following code −

DateTimeIndex...
DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 12:30:50+10:30',
'2021-10-30 22:30:50+10:30', '2021-10-31 08:30:50+10:30',
'2021-10-31 18:30:50+10:30', '2021-11-01 04:30:50+10:30',
'2021-11-01 14:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='10H')
DateTimeIndex frequency...
<10 * Hours>

Normalize (converted the time component to midnight)...
DatetimeIndex(['2021-10-30 00:00:00+10:30', '2021-10-30 00:00:00+10:30',
'2021-10-30 00:00:00+10:30', '2021-10-31 00:00:00+10:30',
'2021-10-31 00:00:00+10:30', '2021-11-01 00:00:00+10:30',
'2021-11-01 00:00:00+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

Advertisements