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 floored resolution
The floor() method in Pandas Timedelta returns a new Timedelta object floored to the specified resolution. For hourly flooring, the freq parameter should be set to 'H', which rounds down to the nearest hour.
Syntax
The basic syntax for the Timedelta floor method ?
timedelta.floor(freq)
Parameters
freq: The frequency string for the floor operation. For hourly resolution, use 'H'.
Creating a Timedelta Object
First, let's create a Timedelta object with days, hours, minutes, and seconds ?
import pandas as pd
# Create a Timedelta object
timedelta = pd.Timedelta('4 days 10 hours 2 min 45 s')
print("Original Timedelta:")
print(timedelta)
Original Timedelta: 4 days 10:02:45
Applying Hourly Floor Resolution
Now let's apply the floor method with hourly frequency to round down to the nearest hour ?
import pandas as pd
# Create a Timedelta object
timedelta = pd.Timedelta('4 days 10 hours 2 min 45 s')
print("Original Timedelta:")
print(timedelta)
# Apply hourly floor resolution
floored_timedelta = timedelta.floor(freq='H')
print("\nTimedelta (hourly floored):")
print(floored_timedelta)
Original Timedelta: 4 days 10:02:45 Timedelta (hourly floored): 4 days 10:00:00
Multiple Examples
Here are more examples showing different time values and their hourly floored results ?
import pandas as pd
# Multiple Timedelta examples
timedeltas = [
pd.Timedelta('2 hours 30 minutes'),
pd.Timedelta('1 day 5 hours 45 minutes'),
pd.Timedelta('23 minutes 15 seconds'),
pd.Timedelta('3 hours 59 minutes 59 seconds')
]
for td in timedeltas:
floored = td.floor(freq='H')
print(f"Original: {td} ? Floored: {floored}")
Original: 0 days 02:30:00 ? Floored: 0 days 02:00:00 Original: 1 days 05:45:00 ? Floored: 1 days 05:00:00 Original: 0 days 00:23:15 ? Floored: 0 days 00:00:00 Original: 0 days 03:59:59 ? Floored: 0 days 03:00:00
Key Points
- The
floor()method always rounds down to the nearest specified unit - Minutes and seconds are discarded when using hourly frequency (
'H') - The days component remains unchanged
- Other frequency options include
'D'(day),'T'(minute),'S'(second)
Conclusion
The Timedelta floor() method with freq='H' efficiently rounds down time durations to the nearest hour. This is particularly useful for time-based data analysis and grouping operations in data processing workflows.
