Python Pandas - Round the Timedelta with daily frequency



To round the Timedelta with specified resolution, use the timestamp.round() method. Set the daily frequency resolution using the freq parameter with value ‘D’.

At first, import the required libraries −

import pandas as pd

TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s. Create a Timedelta object −

timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')

Display the Timedelta −

print("Timedelta...\n", timedelta)

Return the rounded Timestamp with daily frequency. Here, the specified resolution is set using the "freq" parameter −

timedelta.round(freq='D')

Example

Following is the code −

import pandas as pd

# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s
# create a Timedelta object
timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')

# display the Timedelta
print("Timedelta...\n", timedelta)

# return the rounded Timestamp
# with daily frequency
# Here, the specified resolution is set using the "freq" parameter
res = timedelta.round(freq='D')

# display the rounded Timestamp
print("\nTimedelta (daily rounded)...\n", res)

Output

This will produce the following code −

Timedelta...
2 days 11:22:25.050000045

Timedelta (daily rounded)...
2 days 00:00:00

Advertisements