Python - How do I round datetime column to nearest quarter hour?

Given a Pandas DataFrame, we have to round it's datetime column to nearest quarter hour. By Pranit Sharma Last updated : September 26, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose, we have a DataFrame, which consists of several columns but a column contains time values where the time is divided into certain time units, we will round up this time and update each value. DataFrames consist of rows, columns, and data. The Data inside the DataFrame can be of any type.

Rounding datetime column to nearest quarter hour

If we use pd.Timestamp() method and pass a string inside it, it will convert this string into time format. We will use df.round() method and pass the amount of time as a string up to which we need to round up the time value.

Let us understand with the help of an example,

Python program to round dataframe's datetime column to nearest quarter hour

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {'Time':['2013-10-16 08:23:00','2012-05-26 23:12:00','2010-03-06 18:11:00','2022-08-13 15:15:00','2011-05-11 11:44:00','2017-06-26 00:00:00']}

# Creating DataFrame
df = pd.DataFrame(d)

# Display Original DataFrames
print("Created DataFrame:\n",df,"\n")

df['Time'] = pd.to_datetime(df['Time'])

#Rounding of the time value
df['new Time']=df['Time'].dt.round('15min')

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: Round datetime column to nearest quarter hour

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.