Home > Backend Development > Python Tutorial > How Can I Format Dates in a Pandas DataFrame After Converting to datetime64?

How Can I Format Dates in a Pandas DataFrame After Converting to datetime64?

Susan Sarandon
Release: 2024-12-13 17:01:14
Original
581 people have browsed it

How Can I Format Dates in a Pandas DataFrame After Converting to datetime64?

Formatting Dates in Pandas

When importing a dataframe with a datetime column, Pandas may automatically convert it to an object type. To ensure proper formatting, converting the column to a datetime64 type is often necessary. However, this may result in an undesired date format.

Convert Datetime Format

To change the datetime format after converting to datetime64, you can utilize the dt.strftime method. This allows you to specify the desired date format as a string. The resulting dtype will be an object type (string).

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016'}})
df['DOB'] = pd.to_datetime(df['DOB'])
df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
Copy after login

Example

In this example, the DOB column is initially an object type with the format "26/1/2016". After converting it to datetime64, the format becomes "2016-01-26". Using dt.strftime, we create a new column, DOB1, with the preferred format "01/26/2016".

Considerations

Changing the date format to a string will result in an object dtype. This may not be suitable for calculations or other operations that require a datetime type. If preserving the datetime type is essential, consider using custom formatting options within the dt.strftime method to achieve the desired format while maintaining the datetime dtype.

The above is the detailed content of How Can I Format Dates in a Pandas DataFrame After Converting to datetime64?. 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