Home >Backend Development >Python Tutorial >How to Extract Only the Date Part from a pandas.to_datetime Output?

How to Extract Only the Date Part from a pandas.to_datetime Output?

DDD
DDDOriginal
2024-11-11 02:40:021046browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn