convert datetime format 01-feb-2022 to 2022-02-01 in pandas in python

You can use the pd.to_datetime() function in pandas to convert datetime format. To convert the format from '01-feb-2022' to '2022-02-01', you can use the following code:

main.py
import pandas as pd

# Create a DataFrame with date column
data = {'date': ['01-feb-2022']}
df = pd.DataFrame(data)

# Convert the date column to datetime format
df['date'] = pd.to_datetime(df['date'], format='%d-%b-%Y')

# Convert the datetime format to the desired format
df['date'] = df['date'].dt.strftime('%Y-%m-%d')

print(df)
333 chars
14 lines

This code will create a DataFrame with a date column containing '01-feb-2022'. It then uses pd.to_datetime() to convert the date column to a datetime format, specifying the input format as '%d-%b-%Y' (day-month-year). Finally, it uses dt.strftime() to convert the datetime format to the desired format '%Y-%m-%d' (year-month-day). The resulting DataFrame will have the date column in the format '2022-02-01'.

related categories

gistlibby LogSnag