01-jan-2015 format in pandas in python

To convert a date represented as "01-jan-2015" into a desired format using pandas in Python, you can use the to_datetime() function along with strftime().

Here's an example of how you can achieve this:

main.py
import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({'date': ['01-jan-2015', '02-feb-2016', '03-mar-2017']})

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

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

# Print the updated dataframe with the desired date format
print(df)
413 chars
14 lines

Output:

main.py
         date
0  2015-01-01
1  2016-02-02
2  2017-03-03
56 chars
5 lines

In the above code, pd.to_datetime() is used to convert the 'date' column to a pandas datetime object, by specifying the original date format as '%d-%b-%Y'. Then dt.strftime() is used to convert the datetime object to the desired format specified as '%Y-%m-%d'.

related categories

gistlibby LogSnag