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 - How to Round the TimeDeltaIndex with milliseconds frequency
To round the TimeDeltaIndex with milliseconds frequency, use the TimeDeltaIndex.round() method. For milliseconds frequency, use the freq parameter with value 'ms'.
Creating a TimeDeltaIndex
First, import pandas and create a TimeDeltaIndex with timedelta-like data ?
import pandas as pd
# Create a TimeDeltaIndex object with different time formats
tdIndex = pd.TimedeltaIndex(data=['10 day 5h 2 min 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+07:20:32.261811624'])
print("TimedeltaIndex...\n", tdIndex)
TimedeltaIndex...
TimedeltaIndex(['10 days 05:02:00.000003010', '0 days 22:39:19.999999',
'2 days 07:08:02.000045', '0 days 07:20:32.261811624'],
dtype='timedelta64[ns]', freq=None)
Viewing Components
You can examine the individual components (days, hours, minutes, etc.) of the TimeDelta values ?
import pandas as pd
tdIndex = pd.TimedeltaIndex(data=['10 day 5h 2 min 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+07:20:32.261811624'])
print("The Dataframe of the components of TimeDeltas...\n", tdIndex.components)
The Dataframe of the components of TimeDeltas... days hours minutes seconds milliseconds microseconds nanoseconds 0 10 5 2 0 0 3 10 1 0 22 39 19 999 999 0 2 2 7 8 2 0 45 0 3 0 7 20 32 261 811 624
Rounding to Milliseconds
Use the round() method with freq='ms' to round to the nearest millisecond ?
import pandas as pd
tdIndex = pd.TimedeltaIndex(data=['10 day 5h 2 min 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+07:20:32.261811624'])
print("Original TimedeltaIndex...")
print(tdIndex)
print("\nAfter rounding to milliseconds frequency...")
rounded_td = tdIndex.round(freq='ms')
print(rounded_td)
Original TimedeltaIndex...
TimedeltaIndex(['10 days 05:02:00.000003010', '0 days 22:39:19.999999',
'2 days 07:08:02.000045', '0 days 07:20:32.261811624'],
dtype='timedelta64[ns]', freq=None)
After rounding to milliseconds frequency...
TimedeltaIndex(['10 days 05:02:00', '0 days 22:39:20',
'2 days 07:08:02', '0 days 07:20:32.262000'],
dtype='timedelta64[ns]', freq=None)
How Rounding Works
The rounding operation follows standard rounding rules:
- Values less than 0.5ms are rounded down (truncated)
- Values 0.5ms and above are rounded up to the next millisecond
- Microseconds and nanoseconds are removed in the process
Conclusion
Use TimeDeltaIndex.round(freq='ms') to round time deltas to millisecond precision. This removes microseconds and nanoseconds while following standard rounding rules for fractional milliseconds.
Advertisements
