Open In App

Pandas Series dt.round | Round Off DateTime Values to Given Frequency

Improve
Improve
Like Article
Like
Save
Share
Report

The Pandas dt.round() method rounds off the DateTime values in a series to a certain frequency level.

Example:

Python3

import pandas as pd
sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30',
               '2010-1-1 09:25', '2019-12-31 00:00'])
idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
sr.index = idx
sr = pd.to_datetime(sr)
result = sr.dt.round(freq = 'D')
print(result)

Output :

dt.round output

Syntax

Syntax: Series.dt.round(freq, ambiguous=’raise’, nonexistent=’raise’) 

Parameter: 

  • freq: The frequency level to round the index
  • ambiguous: It determines whether the time should be interpreted as wall time (default), the version of the time that was earlier, the version of the time that was later, or raise an error if ambiguous.
  • nonexistent: It determines whether the time should be shifted forward to the closest existing time, shifted backward to the closest existing time, return NaT, or raise an error if nonexistent.

Returns: DatetimeIndex, TimedeltaIndex, or Series of the same type.

How to Round off the DateTime Series Values to a Certain Frequency Level

To round off the DateTime values in a series to a certain frequency level we use the dt.round method of the Pandas library in Python.

Let’s understand it better with an example:

Example:

Use the Series.dt.round() function to round the DateTime data of the given series object to the specified frequency.

Python3



# importing pandas as pd
import pandas as pd

# Creating the Series
sr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'T',
                            tz = 'Asia / Calcutta'))

# Creating the index
idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']

# set the index
sr.index = idx

# Print the series
print(sr)

Output :

datetime series created

Now we will use the dt.round() function to round the datetime values in the given series object to Hourly frequency.

Python3



# round to hourly frequency
result = sr.dt.round(freq = 'H')

# print the result
print(result)

Output :

datetime rounded to hourly frequency

As we can see in the output, the dt.round() function has successfully rounded the DateTime values in the given series object to the specified frequency.


Last Updated : 08 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads