Python Pandas - Return a new Timedelta with seconds ceiling resolution

The timedelta.ceil() method returns a new Timedelta object ceiled to a specified resolution. For seconds ceiling resolution, set the freq parameter to 'S'.

Understanding ceil() Method

The ceil() method rounds up the Timedelta to the nearest unit specified by the frequency parameter. When using 'S' for seconds, any fractional seconds (milliseconds, microseconds, nanoseconds) are rounded up to the next second.

Syntax

timedelta.ceil(freq)

Parameters

  • freq ? String representing the frequency to ceil to. Use 'S' for seconds.

Basic Example

Let's create a Timedelta with fractional seconds and ceil it to seconds resolution ?

import pandas as pd

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

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

# Return the ceiled Timedelta with seconds resolution
ceiled_timedelta = timedelta.ceil(freq='S')

# Display the ceiled Timedelta
print("\nCeiled to seconds:")
print(ceiled_timedelta)
Original Timedelta:
2 days 10:45:20.035000055

Ceiled to seconds:
2 days 10:45:21

How It Works

The original Timedelta has 20 seconds plus 35 milliseconds and 55 nanoseconds. Since there are fractional seconds, the ceil() method rounds up to the next whole second (21 seconds).

Multiple Examples

Here are examples with different fractional second values ?

import pandas as pd

# Example 1: With milliseconds only
td1 = pd.Timedelta('1 hour 30 min 15 s 500 ms')
print("Original:", td1)
print("Ceiled:  ", td1.ceil('S'))

print()

# Example 2: Exact seconds (no change)
td2 = pd.Timedelta('2 hours 45 min 30 s')
print("Original:", td2)
print("Ceiled:  ", td2.ceil('S'))

print()

# Example 3: With microseconds
td3 = pd.Timedelta('5 min 10 s 1 us')
print("Original:", td3)
print("Ceiled:  ", td3.ceil('S'))
Original: 1:30:15.500000
Ceiled:   1:30:16

Original: 2:45:30
Ceiled:   2:45:30

Original: 0:05:10.000001
Ceiled:   0:05:11

Key Points

  • If the Timedelta has exact seconds (no fractional part), it remains unchanged
  • Any fractional seconds cause rounding up to the next second
  • The method returns a new Timedelta object; the original remains unchanged

Conclusion

Use timedelta.ceil(freq='S') to round up Timedelta objects to the nearest second. This is useful for standardizing time intervals by eliminating sub-second precision.

Updated on: 2026-03-26T16:18:54+05:30

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements