How can I convert a datetime to a date in Pandas?

The process of converting a datetime to a date in Pandas involves using the .date() method. This method extracts only the date portion of the datetime object and returns it in a date format. This conversion is useful for performing various operations and analysis on a specific date rather than a specific time. The resulting date object can then be easily manipulated and manipulated using various Pandas methods and functions.

Convert Datetime to Date in Pandas


Often you may want to convert a datetime to a date in pandas. Fortunately this is easy to do using the .dt.date function, which takes on the following syntax:

df['date_column'] = pd.to_datetime(df['datetime_column']).dt.date

Example: Datetime to Date in Pandas

For example, suppose we have the following pandas DataFrame:

import pandas as pd

#create pandas DataFrame with two columns
df = pd.DataFrame({'sales': [4, 11],
                   'time': ['2020-01-15 20:02:58', '2020-01-18 14:43:24']})

#view DataFrame print(df)

sales	time
0	4	2020-01-15 20:02:58
1	11	2020-01-18 14:43:24

To convert the ‘time’ column to just a date, we can use the following syntax:

#convert datetime column to just date
df['time'] = pd.to_datetime(df['time']).dt.date#view DataFrame
print(df)

	sales	time
0	4	2020-01-15
1	11	2020-01-18

Now the ‘time’ column just displays the date without the time.

Using Normalize() for datetime64 Dtypes

You should note that the code above will return an object dtype:

#find dtype of each column in DataFrame
df.dtypes

sales     int64
time     object
dtype:   object

If you instead want datetime64 then you can normalize() the time component, which will keep the dtype as datetime64 but it will only display the date:

#convert datetime column to just date
df['time'] = pd.to_datetime(df['time']).dt.normalize()#view DataFrame
print(df)

	sales	time
0	4	2020-01-15
1	11	2020-01-18

#find dtype of each column in DataFrame
df.dtypes

sales             int64
time     datetime64[ns]
dtype: object

Once again only the date is displayed, but the ‘time’ column is a datetime64 dtype.

Additional Resources

How to Convert Columns to DateTime in Pandas
How to Convert Strings to Float in Pandas

x