Python Pandas - Round the Timedelta with seconds frequency

The Pandas Timedelta object represents differences between two datetime values. You can round a Timedelta to the nearest second using the round() method with frequency parameter 's'.

Syntax

timedelta.round(freq='s')

Where freq='s' specifies seconds frequency for rounding.

Creating a Timedelta Object

First, let's create a Timedelta object with various time components ?

import pandas as pd

# Create a Timedelta object
timedelta = pd.Timedelta('1 days 11 hours 22 min 25 s 50 ms 45 ns')

print("Original Timedelta:")
print(timedelta)
Original Timedelta:
1 days 11:22:25.050000045

Rounding to Seconds Frequency

Use the round() with freq='s' to round to the nearest second ?

import pandas as pd

# Create a Timedelta object
timedelta = pd.Timedelta('1 days 11 hours 22 min 25 s 50 ms 45 ns')

# Round to seconds frequency
rounded_timedelta = timedelta.round(freq='s')

print("Original Timedelta:")
print(timedelta)
print("\nRounded Timedelta (seconds):")
print(rounded_timedelta)
Original Timedelta:
1 days 11:22:25.050000045

Rounded Timedelta (seconds):
1 days 11:22:25

Multiple Examples

Let's see how different Timedelta values round to seconds ?

import pandas as pd

# Create multiple Timedelta objects
timedeltas = [
    pd.Timedelta('2 hours 15 min 30 s 250 ms'),
    pd.Timedelta('5 days 8 hours 45 min 12 s 750 ms'),
    pd.Timedelta('30 min 59 s 999 ms')
]

for i, td in enumerate(timedeltas, 1):
    rounded = td.round(freq='s')
    print(f"Example {i}:")
    print(f"Original:  {td}")
    print(f"Rounded:   {rounded}")
    print()
Example 1:
Original:  0 days 02:15:30.250000
Rounded:   0 days 02:15:30

Example 2:
Original:  5 days 08:45:12.750000
Rounded:   5 days 08:45:13

Example 3:
Original:  0 days 00:30:59.999000
Rounded:   0 days 00:31:00

Key Points

  • The round() method rounds to the nearest specified frequency
  • Milliseconds and nanoseconds are removed when rounding to seconds
  • Values ? 500ms round up to the next second
  • Values < 500ms round down to the current second

Conclusion

Use timedelta.round(freq='s') to round Timedelta objects to the nearest second. This removes sub-second precision and follows standard rounding rules where values ? 500ms round up.

Updated on: 2026-03-26T16:23:14+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements