How to reformat dates in pandas?

Published on Aug. 22, 2023, 12:18 p.m.

To reformat dates in a pandas DataFrame, you first need to convert them to the datetime format using pd.to_datetime(). Once the dates are in the datetime format, you can use the .dt accessor to access different date components such as year, month, day, and time. Finally, you can use the strftime() method to reformat the dates.

Here is an example of how to reformat dates in pandas:

import pandas as pd

# Create a DataFrame with a date column
df = pd.DataFrame({'date': ['2022-08-15', '2022-08-16', '2022-08-17'], 'value': [1, 2, 3]})

# Convert the date column to datetime format
df['date'] = pd.to_datetime(df['date'])

# Reformat the date column as dd-mm-yyyy
df['date'] = df['date'].dt.strftime('%d-%m-%Y')

# Print the updated DataFrame
print(df)

In this code, we create a pandas DataFrame df with a date column in the YYYY-MM-DD format. We first convert the date column to the datetime format using pd.to_datetime(). Then, we use the .dt accessor to access the day, month, and year components of the date, and use .strftime() to reformat the date as dd-mm-yyyy.

Note that the strftime() function uses the same format codes as the standard Python datetime module.

Tags: