Python Pandas - Round the Timedelta with hourly frequency

To round a Timedelta with specified resolution, use the timedelta.round() method. Set the hourly frequency resolution using the freq parameter with value 'H'.

Syntax

timedelta.round(freq)

Parameters:

  • freq − Frequency string like 'H' for hours, 'T' for minutes, 'S' for seconds

Example

Let's create a Timedelta object and round it to the nearest hour ?

import pandas as pd

# Create a Timedelta object
timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')

# Display the original Timedelta
print("Original Timedelta:")
print(timedelta)

# Round to hourly frequency
rounded_timedelta = timedelta.round(freq='H')

# Display the rounded Timedelta
print("\nRounded Timedelta (hourly):")
print(rounded_timedelta)
Original Timedelta:
2 days 10:45:20.035000055

Rounded Timedelta (hourly):
2 days 11:00:00

How It Works

The round() method rounds the Timedelta to the nearest specified frequency. Since our original time was 10:45:20, it rounds up to 11:00:00 because 45 minutes is closer to the next hour than the previous hour.

Different Frequency Options

You can use different frequency strings for various rounding resolutions ?

import pandas as pd

timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')

print("Original:", timedelta)
print("Rounded to hours:", timedelta.round(freq='H'))
print("Rounded to minutes:", timedelta.round(freq='T'))
print("Rounded to seconds:", timedelta.round(freq='S'))
Original: 2 days 10:45:20.035000055
Rounded to hours: 2 days 11:00:00
Rounded to minutes: 2 days 10:45:00
Rounded to seconds: 2 days 10:45:20

Common Frequency Strings

Frequency String Description
Hour 'H' Round to nearest hour
Minute 'T' or 'min' Round to nearest minute
Second 'S' Round to nearest second
Millisecond 'L' or 'ms' Round to nearest millisecond

Conclusion

Use timedelta.round(freq='H') to round Timedelta objects to the nearest hour. The method supports various frequency strings for different time resolutions, making it useful for time-based data analysis and formatting.

Updated on: 2026-03-26T16:22:19+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements