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 milliseconds floored resolution
To return a new Timedelta floored to this resolution, use the timedelta.floor() method. For milliseconds floored resolution, set the freq parameter to 'ms'.
Syntax
timedelta.floor(freq)
Parameters
freq: String representing the frequency. Use 'ms' for milliseconds resolution.
Example
Let's create a Timedelta object and floor it to milliseconds resolution ?
import pandas as pd
# Create a Timedelta object with nanoseconds 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)
# Floor to milliseconds resolution
floored_timedelta = timedelta.floor(freq='ms')
# Display the floored Timedelta
print("\nFloored to milliseconds:")
print(floored_timedelta)
Original Timedelta: 2 days 10:45:20.035000055 Floored to milliseconds: 2 days 10:45:20.035000
How It Works
The floor() method removes precision below the specified frequency. When using 'ms', it truncates nanoseconds, keeping only milliseconds precision. In our example, the original 55 nanoseconds are removed, leaving only the milliseconds component.
Other Frequency Options
import pandas as pd
timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')
print("Original:", timedelta)
print("Seconds floored:", timedelta.floor('s'))
print("Minutes floored:", timedelta.floor('min'))
print("Hours floored:", timedelta.floor('h'))
Original: 2 days 10:45:20.035000055 Seconds floored: 2 days 10:45:20 Minutes floored: 2 days 10:45:00 Hours floored: 2 days 10:00:00
Conclusion
The floor() method with freq='ms' truncates Timedelta precision to milliseconds. Use different frequency values like 's', 'min', or 'h' for other resolutions.
