Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 484
j robertson Avatar asked Aug 02 '18 19:08

j robertson


People also ask

How do you round a Timedelta?

To round the Timedelta with specified resolution, use the timestamp. round() method.

What is the use of Timedelta () function?

timedelta() function. Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.

What does Timedelta mean in Python?

Python timedelta class. The timedelta is a class in datetime module that represents duration. The delta means average of difference and so the duration expresses the difference between two date, datetime or time instances. By using timedelta, you may estimate the time for future and past.


1 Answers

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):

  • How do I round datetime column to nearest quarter hour
  • Rounding Pandas Timestamp to minutes
like image 71
TimK Avatar answered Sep 20 '22 18:09

TimK