how to convert date from format 1 may 2023 to 1-5-2023 in python pandas in python

You can use the pandas.to_datetime() method to convert the date string to a datetime object and then format it using the strftime() method. Here's an example:

main.py
import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({'date': ['1 may 2023', '2 jun 2024', '3 jul 2025']})

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

# format the date column
df['date'] = df['date'].dt.strftime('%-d-%-m-%Y')

# show the updated DataFrame
print(df)
323 chars
14 lines

Output:

main.py
         date
0   1-5-2023
1   2-6-2024
2   3-7-2025
53 chars
5 lines

Note: the "%-d" and "%-m" format codes are used to remove leading zeros from the day and month values respectively.

related categories

gistlibby LogSnag