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 seconds floored resolution
To return a new Timedelta floored to this resolution, use the timedelta.floor() method. For seconds floored resolution, set the freq parameter to 'S'.
What is Timedelta Flooring?
Flooring a Timedelta means rounding down to the nearest specified time unit. When you floor to seconds resolution, all sub-second components (milliseconds, microseconds, nanoseconds) are removed.
Syntax
timedelta.floor(freq)
Parameters:
-
freq ? The frequency string. Use
'S'for seconds resolution.
Example
Let's create a Timedelta object with various time components and floor it to seconds resolution ?
import pandas as pd
# Create a Timedelta object with sub-second precision
timedelta = pd.Timedelta('4 days 11 hours 38 min 20 s 35 ms 55 ns')
# Display the original Timedelta
print("Original Timedelta...")
print(timedelta)
# Floor to seconds resolution
floored_timedelta = timedelta.floor(freq='S')
# Display the floored Timedelta
print("\nTimedelta (seconds floored)...")
print(floored_timedelta)
Original Timedelta... 4 days 11:38:20.035000055 Timedelta (seconds floored)... 4 days 11:38:20
How It Works
The floor() method removes all time components smaller than the specified frequency. In this example:
- Original: 4 days 11:38:20.035000055 (includes milliseconds and nanoseconds)
- Floored: 4 days 11:38:20 (sub-second components removed)
Other Frequency Options
You can floor to different resolutions using various frequency strings ?
import pandas as pd
timedelta = pd.Timedelta('2 days 15 hours 45 min 30 s 500 ms')
print("Original:", timedelta)
print("Minutes floored:", timedelta.floor(freq='T'))
print("Hours floored:", timedelta.floor(freq='H'))
print("Days floored:", timedelta.floor(freq='D'))
Original: 2 days 15:45:30.500000 Minutes floored: 2 days 15:45:00 Hours floored: 2 days 15:00:00 Days floored: 2 days 00:00:00
Conclusion
The floor() method with freq='S' removes sub-second precision from Timedelta objects. Use different frequency strings like 'T', 'H', or 'D' to floor to minutes, hours, or days respectively.
