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