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
Selected Reading
Python Pandas - Round the Timedelta with specified resolution
To round a Timedelta with specified resolution in Pandas, use the round() method. The freq parameter controls the rounding resolution such as seconds, minutes, or hours.
Syntax
timedelta.round(freq)
Parameters:
- freq − The frequency string ('s' for seconds, 'min' for minutes, 'h' for hours, etc.)
Creating a Timedelta Object
First, let's create a Timedelta object with various time components ?
import pandas as pd
# Create a Timedelta object with days, hours, minutes, seconds, milliseconds, and nanoseconds
timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')
print("Original Timedelta:")
print(timedelta)
Original Timedelta: 2 days 10:45:20.035000055
Rounding to Different Resolutions
Rounding to Seconds
import pandas as pd
timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')
# Round to seconds
rounded_seconds = timedelta.round(freq='s')
print("Rounded to seconds:", rounded_seconds)
Rounded to seconds: 2 days 10:45:20
Rounding to Minutes
import pandas as pd
timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')
# Round to minutes
rounded_minutes = timedelta.round(freq='min')
print("Rounded to minutes:", rounded_minutes)
Rounded to minutes: 2 days 10:45:00
Rounding to Hours
import pandas as pd
timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')
# Round to hours
rounded_hours = timedelta.round(freq='h')
print("Rounded to hours:", rounded_hours)
Rounded to hours: 2 days 11:00:00
Common Frequency Parameters
| Frequency | Description | Example |
|---|---|---|
| 's' | Seconds | Rounds to nearest second |
| 'min' | Minutes | Rounds to nearest minute |
| 'h' | Hours | Rounds to nearest hour |
| 'D' | Days | Rounds to nearest day |
Complete Example
import pandas as pd
# Create a Timedelta object
timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')
print("Original Timedelta:", timedelta)
# Round to different resolutions
print("Rounded to seconds:", timedelta.round(freq='s'))
print("Rounded to minutes:", timedelta.round(freq='min'))
print("Rounded to hours:", timedelta.round(freq='h'))
print("Rounded to days:", timedelta.round(freq='D'))
Original Timedelta: 2 days 10:45:20.035000055 Rounded to seconds: 2 days 10:45:20 Rounded to minutes: 2 days 10:45:00 Rounded to hours: 2 days 11:00:00 Rounded to days: 2 days 00:00:00
Conclusion
Use timedelta.round(freq) to round Timedelta objects to specified resolutions. Common frequencies include 's' for seconds, 'min' for minutes, and 'h' for hours, providing flexible time precision control.
Advertisements
