Python Pandas - Round the Timedelta with hourly frequency


To round the Timedelta with specified resolution, use the timestamp.round() method. Set the hourly frequency resolution using the freq parameter with value H.

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 10 hours 45 min 20 s 35 ms 55 ns')

Display the Timedelta

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

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

timedelta.round(freq='H')

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 10 hours 45 min 20 s 35 ms 55 ns')

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

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

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

Output

This will produce the following code

Timedelta...
2 days 10:45:20.035000055

Timedelta (hourly rounded)...
2 days 11:00:00

Updated on: 14-Oct-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements