Home >Backend Development >Python Tutorial >How to Extract Only the Date Part from a pandas.to_datetime Output?
Keep Only Date Part in Pandas to_datetime Output
When parsing dates using pandas.to_datetime, Pandas represents the dates in datetime64[ns] format even if they are daily only. To keep only the date part and avoid appending the time component, there are two elegant solutions:
Date Component Extraction:
Since Pandas version 0.15.0, the dt accessor provides access to just the date component:
df['just_date'] = df['dates'].dt.date
This returns datetime.date objects with the object datatype.
Datetime64 Normalization:
To keep the datetime64 datatype, you can normalize the dates to midnight:
df['normalised_date'] = df['dates'].dt.normalize()
This sets the time component to 00:00:00, but the display shows only the date value. This method preserves the datetime64 datatype.
Note:
For more flexibility, refer to the Pandas documentation on pandas.Series.dt.
The above is the detailed content of How to Extract Only the Date Part from a pandas.to_datetime Output?. For more information, please follow other related articles on the PHP Chinese website!