Pandas convert DateTime to date in Python

Pandas convert DateTime to date

Being able to convert a datetime64 object in Pandas to just the date can make it easier to understand and work with. In this post, I will show you how to do this simply in multiple variants.

Stephen Allwright
Stephen Allwright

Being able to convert a datetime64 object in Pandas to just the date can make it easier to understand and work with. In this post, I will show you how to do this simply in multiple variants.

How to convert a datetime64 Pandas object to date in Python

It’s simple to convert a Pandas datetime64 object to just the date in Python, to do so all you need to do is use the .dt.date method on the DateTime column in question.

convert a datetime64 Pandas object to date in Python

Let’s look at some examples.

Pandas convert DateTime to date

The most common way of converting a DateTime column in Pandas to just the date is by using the .dt.date method.

This example shows a simple implementation of the method.

import pandas as pd

df = pd.DataFrame()

df['datetime'] = pd.to_datetime(
	['2022-09-15 09:01:20', '2022-05-02 18:21:58', '2022-07-22 13:47:12']
	)

df['date'] = df['datetime'].dt.date

print(df)
print(df.dtypes)

"""
Output:

datetime               date
0 2022-09-15 09:01:20  2022-09-15
1 2022-05-02 18:21:58  2022-05-02
2 2022-07-22 13:47:12  2022-07-22

datetime    datetime64[ns]
date                object
"""

Convert Pandas DateTime to date but keep data type

Using .dt.date will return the column as an object data type, which has limitations. If you however want to keep the column as a datetime64 data type then you need to use either .normalize() or round to the nearest day by using .round() . Let’s look at an example of these in action.

import pandas as pd

df = pd.DataFrame()

df['datetime'] = pd.to_datetime(
	['2022-09-15 09:01:20', '2022-05-02 18:21:58', '2022-07-22 13:47:12']
	)

df['date_round'] = df['datetime'].dt.round("D")
df['date_normalize'] = df['datetime'].dt.normalize()

print(df)
print(df.dtypes)

"""
Output:

datetime                date_round    date_normalize
0 2022-09-15 09:01:20   2022-09-15    2022-09-15
1 2022-05-02 18:21:58   2022-05-03    2022-05-02
2 2022-07-22 13:47:12   2022-07-23    2022-07-22

datetime          datetime64[ns]
date_round        datetime64[ns]
date_normalize    datetime64[ns]
"""

Pandas round DateTime to day
Pandas round DateTime to week
Pandas round DateTime to month
Python get week number from datetime
Python get month from date

References

Pandas normalize documentation
Pandas round documentation

Pandas

Stephen Allwright Twitter

I'm a Data Scientist currently working for Oda, an online grocery retailer, in Oslo, Norway. These posts are my way of sharing some of the tips and tricks I've picked up along the way.