Home >Backend Development >Python Tutorial >How to Extract Only the Date Component from a Pandas Datetime Series?

How to Extract Only the Date Component from a Pandas Datetime Series?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 16:40:12915browse

How to Extract Only the Date Component from a Pandas Datetime Series?

Parsing Dates with pandas: Keeping Only the Date Component

When using pandas.to_datetime to parse dates, pandas by default represents them as datetime64[ns], even if the dates are daily-only. This can lead to undesired appending of "00:00:00" when writing the data to CSV.

Converting to datetime.date or datetime64[D]

To convert the dates to datetime.date or datetime64[D], there are a few options:

  • Looping Through Elements: Manually converting each element using dt.to_datetime().date() is possible but slow for large datasets.
  • Using .dt Attribute: Since Pandas version 0.15.0, you can use the .dt attribute to access only the date component:
df['just_date'] = df['dates'].dt.date

This will return datetime.date objects with an object dtype.

  • Normalization: To keep the dtype as datetime64, you can normalize the dates:
df['normalised_date'] = df['dates'].dt.normalize()

This will set the time component to midnight (00:00:00), but the display will still show only the date value.

Precision Specification:

pandas.to_datetime does not yet support precision specification. However, the aforementioned methods provide alternative ways to obtain the desired date representation.

The above is the detailed content of How to Extract Only the Date Component from a Pandas Datetime Series?. 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