How to return only the date from DateTime column in pandas
Overview
We can extract the date from a datetime column in the following ways:
- The
.dtaccessor - The
normalize()method
The .dt accessor
The .dt accessor method is used to access the datetime-like properties for the series.
Note: We can refer to .dt accessor to learn more about
.dtaccessor.
Code example
Let’s look at the code below:
import pandas as pddf = pd.DataFrame({"timestamp": ["2013-01-01 09:10:12", "2022-01-02 09:10:12", "2022-01-03 09:10:12", "2022-01-04 09:10:12"]})print(pd.to_datetime(df['timestamp']).dt.date)
Code explanation
- Line 1: We import the
pandasmodule. - Line 3: We create a dataframe
dfwith atimestampcolumn. - Line 5: We access the date part of the
timestampcolumn by accessing thedateofdtaccessor.
The normalize() method
The normalize() method converts times to midnight. It sets all the values to 00:00:00.
Code example
Let’s look at the code below:
import pandas as pddf = pd.DataFrame({"timestamp": ["2013-01-01 09:10:12", "2022-01-02 09:10:12", "2022-01-03 09:10:12", "2022-01-04 09:10:12"]})print(pd.to_datetime(df['timestamp']).dt.normalize())
Code explanation
- Line 1: We import the
pandasmodule. - Line 3: We create a dataframe
dfwith atimestampcolumn. - Line 5: We access the date part of the
timestampcolumn by invoking thenormalize()function of thedtaccessor.