how to change the format of pandas datetime from 30-nov-2023 to 30-11-2023 in python

To change the format of a pandas datetime column from "30-nov-2023" to "30-11-2023" in Python, you can use the to_datetime function from pandas along with the dt accessor to format the datetime values.

Here is an example:

main.py
import pandas as pd

# Create a sample DataFrame with date column
df = pd.DataFrame({'date': ['30-nov-2023', '15-dec-2023', '22-jan-2024']})

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

# Change the date format using datetime formatting
df['date'] = df['date'].dt.strftime('%d-%m-%Y')

# Print the updated DataFrame
print(df)
368 chars
14 lines

This will give the output:

main.py
         date
0  30-11-2023
1  15-12-2023
2  22-01-2024
56 chars
5 lines

In the above code, we first convert the 'date' column to datetime format using pd.to_datetime(). Then, we use the dt.strftime() method to change the date format to '%d-%m-%Y' (day-month-year). Finally, we assign the updated date column back to the DataFrame.

related categories

gistlibby LogSnag