How to convert a column to Datetime in Pandas

Spread the love

Problem –

You have a column which contains dates but the data has been read as Object type instead of Datetime and you want to convert it into Datetime.

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()

If you check the dataframe at this moment, you can see that the Date column is read as object type.

df.dtypes

Method 1 –

To convert the Date object type column to Datetime, we can use the pd.to_datetime() function in pandas.

df['Date'] = pd.to_datetime(df['Date'])
df['Date']

Here, I do not have the timestamp, that is why pandas only showing the Date part.

Method 2 –

Another way to convert a datetime object column to datetime is using astype method in pandas.

df['Date'] = df['Date'].astype('datetime64[ns]')
df['Date']

For more Info about astype – Pandas – astype() – Change column data type in pandas

Method 3 –

Another method for converting a column to datetime is using apply method.

from datetime import datetime
df['Date'].apply(lambda val: datetime.strptime(val, "%Y-%m-%d"))

For more info about apply – Pandas – How apply() function works in pandas

Rating: 1 out of 5.

Leave a Reply