Truncate timestamp column to hour precision in pandas dataframe

Given a pandas dataframe, we have to truncate timestamp column to hour precision.
Submitted by Pranit Sharma, on September 13, 2022

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.

Truncating timestamp column to hour precision

Suppose, we have a DataFrame with a column of Timestamp. We need to find out the hour precision from this timestamp column.

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 code 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


Example: Truncate timestamp column to hour precision

Python Pandas Programs »


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.