change format of date in pandas dataframe from 2023-04-10 to 01-jan-2015 in python

To change the format of a date in a pandas DataFrame, you can use the to_datetime function from the pandas library along with the strftime function from the datetime library to format the date as desired.

Here's an example of how you can change the format of a date column in a pandas DataFrame from "2023-04-10" to "01-jan-2015":

main.py
import pandas as pd
from datetime import datetime

# Create a sample DataFrame
df = pd.DataFrame({'date': ['2023-04-10', '2024-05-15', '2025-06-20']})

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

# Change the format of the date column using strftime
df['date'] = df['date'].dt.strftime('%d-%b-%Y')

# Print the updated DataFrame
print(df)
383 chars
15 lines

Output:

main.py
         date
0  10-Apr-2023
1  15-May-2024
2  20-Jun-2025
59 chars
5 lines

In this example, we first convert the 'date' column to datetime format using pd.to_datetime(). Then, we use dt.strftime() to change the format of the date to '%d-%b-%Y', where '%d' represents the day, '%b' represents the abbreviated month name, and '%Y' represents the year in 4 digits.

related categories

gistlibby LogSnag