How to change the datetime format in pandas

Spread the love

Problem –

You have a datetime column in pandas but you want to change the datetime format other than what is given.

Solution –

Reading a dataset to work with.

import pandas as pd

url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/ICICIBANK.NS.csv"
df = pd.read_csv(url)
df.head()

At this moment, the Date is in – Year-Month-Day format. And let’s say that you want to convert it to Day-Month-Year format.

To do the conversion, first you have to convert the column to datetime type if it is not then use dt.strftime to get the desired format

pd.to_datetime(df['Date']).dt.strftime("%d-%m-%Y")

Note, the resulting Date column will be a string or object type.

1 . How to convert a column to datetime in pandas.

Rating: 1 out of 5.

Leave a Reply