Home  >  Article  >  Backend Development  >  How Do I Extract Only the Date Portion from Pandas Timestamps?

How Do I Extract Only the Date Portion from Pandas Timestamps?

Linda Hamilton
Linda HamiltonOriginal
2024-11-11 00:22:03194browse

How Do I Extract Only the Date Portion from Pandas Timestamps?

Keep Only the Date Portion with Pandas

When using pandas.to_datetime to parse dates, the resulting timestamps include both date and time components. However, for daily data, only the date portion is relevant. Manually converting each date to datetime.date or datetime64[D] is inefficient.

Elegant Solution for Date-Only Data

Fortunately, since Pandas version 0.15.0, you can easily access only the date component using df['dates'].dt.date. This returns datetime.date objects, which are stored as Python objects (dtype object).

Datetime64 Normalization

If you prefer to keep the datetime64 dtype, you can normalize the timestamps to midnight (00:00:00) using df['dates'].dt.normalize(). This sets the time component to zero while preserving the date value.

Additional Resources

  • [Pandas documentation on dt](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.html)

The above is the detailed content of How Do I Extract Only the Date Portion from Pandas Timestamps?. 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