MEHMET BALIOGLU

Remove TIME from DATETIME value in Python

remove time from date in python

In this article, I am going to show you how to remove time from datetime value in Python. It is possible to remove time from datetime value in Python with just a few lines of code..But it can be tricky if you don’t follow the necessary steps.

This is what we want to achieve:

Remove TIME from DATETIME value in Python

Here, time is displayed with date. However, we only need the dates and want to remove time.

import datetime as dt
import pandas as pd

#create dataframe
date_with_time=pd.date_range('2030-02-24', periods=5, freq='T')
df = pd.DataFrame({ 'date': date_with_time}) 

#first: define the format of date column in the dataframe
df['date'] = pd.to_datetime(df.date, format='%Y-%m-%d %H:%M:%S')
#second: convert to the desired date format
df['date']=df['date'].dt.strftime('%d-%m-%Y')
#print first five rows
print(df)

.strftime enables us to convert a datetime format. However, just here there is a tricky part. You need to define the format of the date column. We do this by using .to_datetime. Just be careful to match the format with the existing format of your data. So, if we have 2030-02-24 00:01:00 , we add the following format parameter as displayed above: ‘format=’%Y-%m-%d %H:%M:%S’

After defining the format of the date column, we can now easily convert it to our desired shape:

df['date']=df['date'].dt.strftime('%d-%m-%Y')

If you skip the datetime conversion, you will get the infamous AttributeError: Can only use .dt accessor with datetimelike values

That’s all.