How to Round Time to the Nearest Quarter or Hour in Pandas?

To round a datetime column to the nearest quarter, minute or hour in Pandas, we can use the method: dt.round().

round datetime column to nearest hour

Below you can find an example of rounding to the closest hour in Pandas and Python. We use method dt.round() with parameter H:

import pandas as pd

dates = ['2023-03-25 11:37:00', '2023-03-25 09:18:00', '2023-03-25 15:23:00']
df = pd.DataFrame({'date': dates})
df['date'] = pd.to_datetime(df['date'])

df['date'].dt.round('H')

the result is rounded times to the nearest hour:

0   2023-03-25 12:00:00
1   2023-03-25 09:00:00
2   2023-03-25 15:00:00
Name: date, dtype: datetime64[ns]

round datetime to nearest quarter or minutes

We can round to the nearest quarter in Pandas by the same method: .dt.round('15min') specifying the interval in minutes. Example of rounding down in Pandas to N minutes:

import pandas as pd

dates = ['2023-03-25 11:37:00', '2023-03-25 09:18:00', '2023-03-25 15:23:00']
df = pd.DataFrame({'date': dates})
df['date'] = pd.to_datetime(df['date'])

df['date'].dt.round('15min')

result of rounding to quarter is:

0   2023-03-25 11:30:00
1   2023-03-25 09:15:00
2   2023-03-25 15:30:00
Name: date, dtype: datetime64[ns]

In the next section you can find a link to all possible frequency values.

datetime - round vs floor

Finally let's see what is the difference between Pandas methods:

  • round
  • floor
df['rounded_date'] = df['date'].dt.round('H')

df['floored_date'] = df['date'].dt.floor('H')

You can find the result below:

date rounded_date floored_date
0 2023-03-25 11:37:00 2023-03-25 12:00:00 2023-03-25 11:00:00
1 2023-03-25 09:18:00 2023-03-25 09:00:00 2023-03-25 09:00:00
2 2023-03-25 15:23:00 2023-03-25 15:00:00 2023-03-25 15:00:00

So difference is in the first row where:

  • 12:00:00 - round the datetime column to the nearest hour
  • 11:00:00 - floor the datetime column to the nearest hour

Resources