Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Pandas - Return a new Timedelta with hourly ceiling resolution
To return a new Timedelta ceiled to this resolution, use the timedelta.ceil() method. For hourly ceiling resolution, set the freq parameter to 'H'.
What is Ceiling Operation?
The ceiling operation rounds up a Timedelta to the nearest specified frequency. For hourly ceiling, any fractional hours are rounded up to the next full hour.
Syntax
timedelta.ceil(freq)
Parameters:
- freq: Frequency string (e.g., 'H' for hour, 'min' for minute, 'S' for second)
Example
Let's create a Timedelta object and apply hourly ceiling ?
import pandas as pd
# Create a Timedelta object with fractional hours
timedelta = pd.Timedelta('6 days 11 hours 1 min 30 s')
# Display the original Timedelta
print("Original Timedelta:")
print(timedelta)
# Return the ceiled Timedelta with hourly resolution
ceiled_timedelta = timedelta.ceil(freq='H')
# Display the ceiled Timedelta
print("\nHourly Ceiled Timedelta:")
print(ceiled_timedelta)
Original Timedelta: 6 days 11:01:30 Hourly Ceiled Timedelta: 6 days 12:00:00
How It Works
The original Timedelta has 11 hours, 1 minute, and 30 seconds. Since there are fractional components beyond the hour (1 min 30 s), the ceiling operation rounds up to the next full hour, resulting in 12 hours.
Multiple Examples
import pandas as pd
# Different Timedelta examples
examples = [
pd.Timedelta('2 hours 30 minutes'),
pd.Timedelta('1 day 5 hours 45 minutes'),
pd.Timedelta('3 hours') # Exact hour
]
for i, td in enumerate(examples, 1):
ceiled = td.ceil(freq='H')
print(f"Example {i}:")
print(f"Original: {td}")
print(f"Ceiled: {ceiled}")
print()
Example 1: Original: 0 days 02:30:00 Ceiled: 0 days 03:00:00 Example 2: Original: 1 days 05:45:00 Ceiled: 1 days 06:00:00 Example 3: Original: 0 days 03:00:00 Ceiled: 0 days 03:00:00
Conclusion
The ceil(freq='H') method rounds up any Timedelta to the next full hour. If the Timedelta is already an exact hour, it remains unchanged.
