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
Release: 2024-11-11 02:40:02
Original
1048 people have browsed it

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
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template