Python Pandas - Return a new Timedelta with milliseconds ceiling resolution

To return a new Timedelta ceiled to this resolution, use the timedelta.ceil() method. For milliseconds ceiling resolution, set the freq parameter to 'ms'.

The ceil() method rounds up the Timedelta to the nearest specified frequency unit, effectively removing precision below that unit.

Syntax

timedelta.ceil(freq)

Parameters

freq: Frequency string representing the ceiling resolution. For milliseconds, use 'ms'.

Example

Let's create a Timedelta object and apply milliseconds ceiling resolution ?

import pandas as pd

# Create a Timedelta object with nanosecond precision
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 milliseconds ceiling resolution
result = timedelta.ceil(freq='ms')

# Display the ceiled Timedelta
print("\nTimedelta (milliseconds ceiled):")
print(result)

The output of the above code is ?

Original Timedelta:
2 days 10:45:20.035000055

Timedelta (milliseconds ceiled):
2 days 10:45:20.036000

How It Works

The ceil() method rounds up the Timedelta to the next millisecond boundary. In the example above:

  • Original: 2 days 10:45:20.035000055 (35 ms + 55 ns)
  • Ceiled: 2 days 10:45:20.036000 (rounded up to 36 ms)

Since there were nanoseconds (55 ns) present, the milliseconds value was increased from 35 to 36.

Additional Examples

Here are more examples with different Timedelta values ?

import pandas as pd

# Example with exact milliseconds (no rounding needed)
td1 = pd.Timedelta('1 day 5 hours 30 min 15 s 250 ms')
print("Exact milliseconds:")
print(f"Original: {td1}")
print(f"Ceiled: {td1.ceil(freq='ms')}")

print()

# Example with microseconds that need rounding
td2 = pd.Timedelta('3 hours 12 min 8 s 123 ms 456 us')
print("With microseconds:")
print(f"Original: {td2}")
print(f"Ceiled: {td2.ceil(freq='ms')}")

The output of the above code is ?

Exact milliseconds:
Original: 1 days 05:30:15.250000
Ceiled: 1 days 05:30:15.250000

With microseconds:
Original: 0 days 03:12:08.123456
Ceiled: 0 days 03:12:08.124000

Conclusion

The ceil(freq='ms') method rounds up Timedelta values to millisecond precision, removing any nanosecond or microsecond components. Use this when you need consistent millisecond-level timing resolution in your data processing.

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

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements