j robertson
j robertson

Reputation: 161

using the timedelta.round() function

I've seen multiple questions asked on how to define your own function that does things similar to this, but I can't figure out how to use timedelta's built in function. Does anyone have an example of a use of timedelta.round()? I have timedelta objects that I want to round to the closest full-day.

Documentation at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timedelta.round.html is:

Timedelta.round

Round the Timedelta to the specified resolution

Parameters:

freq : a freq string indicating the rounding resolution

Returns: a new Timedelta rounded to the given resolution of freq

Raises: ValueError if the freq cannot be converted

Upvotes: 11

Views: 18738

Answers (2)

TimK
TimK

Reputation: 615

This question is already answered, but I put it a MWE in for better understanding:

import pandas as pd
df = pd.Series(pd.to_timedelta([
        '0 days +01:01:02.123',
        '0 days +04:03:04.651']))
df.dt.round('5s')  #Rounds to 5sec

Output would be:

0   01:01:00
1   04:03:05
dtype: timedelta64[ns]

Other useful and connected question (timedelta is similar in usage to datetime):

Upvotes: 11

j robertson
j robertson

Reputation: 161

I've answered my own question. The solution was just the string 'd' as a parameter, whereas I was trying 'day','days', etc. Hope this helps someone in need.

Upvotes: 5

Related Questions