Home > Backend Development > Python Tutorial > How to Strip Time Information from Dates Using pandas.to_datetime?

How to Strip Time Information from Dates Using pandas.to_datetime?

Patricia Arquette
Release: 2024-11-12 04:35:01
Original
1016 people have browsed it

How to Strip Time Information from Dates Using pandas.to_datetime?

Stripping Time Information When Using pandas.to_datetime

When parsing dates with pandas.to_datetime, the default representation includes time information, even when the data only contains daily values. This can lead to undesirable results when exporting to CSV, as the dates are appended with 00:00:00.

Efficient Date-Only Conversion

To address this, pandas provides an elegant solution through its .dt accessory. This allows you to access specific date or time components of the datetime object. For example, to extract only the date portion while maintaining the datetime64 dtype, use:

df['normalised_date'] = df['dates'].dt.normalize()
Copy after login

This normalizes the time component to midnight (00:00:00) while preserving the date information in datetime64 format.

Alternatively, for Plain Date Format:

If you prefer to store the dates in datetime.date format with object dtype, use:

df['just_date'] = df['dates'].dt.date
Copy after login

This converts the dates to datetime.date objects, which show only the date value.

By leveraging the .dt accessory, you can efficiently convert dates to either datetime64[D] or datetime.date formats, resolving the issue of unwanted time information in your output.

The above is the detailed content of How to Strip Time Information from Dates Using pandas.to_datetime?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template