Home »
Python »
Python Programs
Dropping time from datetime in Pandas
Learn how to drop time from datetime in Python Pandas?
Submitted by Pranit Sharma, on November 29, 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.
Problem statement
Suppose we are given a data frame and this data frame contains some columns and it has a column of DateTime where the dates it contains is in DateTime format.
Dropping time from datetime
We need to drop the trivial hour from this date-time format so we need to find a way we can only have the year month and day. The quickest way to achieve this goal is to use DateTimeIndexe's normalize() method. We will pass the date column inside the date time index method and apply the normalized method on it also we can store the result in a new column and it will return only the date value.
Let us understand with the help of an example,
Python program to drop time from datetime
# Importing pandas package
import pandas as pd
# Importing numpy package
import numpy as np
# Creating a dictionary
d = {"datetime": pd.date_range('2016-02-02', periods=5, freq='H')}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display original DataFrame
print("Original DataFrame:\n",df,"\n")
# Normalizing datetime
df['Only Date'] = pd.DatetimeIndex(df.datetime).normalize()
# Display result
print("New DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »