Truncate timestamp column to hour precision in pandas dataframe

Given a pandas dataframe, we have to truncate timestamp column to hour precision. By Pranit Sharma Last updated : September 30, 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 with a column of Timestamp. We need to find out the hour precision from this timestamp column.

Truncating timestamp column to hour precision

For this purpose, we will access all the values of the timestamp column and we will typecast each value to a precise hour value. The timestamp value is that value that contains the date and time values in a particular format. It comes from the Datetime library. If we use pd.Timestamp() method and pass a string inside it, it will convert this string into time format. But here, we are going to use the astype() method inside which we pass a format for hour precision.

Let us understand with the help of an example,

Python program to truncate timestamp column to hour precision in pandas dataframe

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {'timestamp':['2010-10-01 11:20:44','2011-04-05 08:42:45','2012-12-11 11:42:00']}

# Creating a DataFrame
df = pd.DataFrame(d)

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

# Getting exact hour value and storing in another column
df['Next'] = df['timestamp'].values.astype('<M8[h]')

# Display result
print("Result:\n",df)

Output

The output of the above program is:

Example: Truncate timestamp column to hour precision

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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