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 = ""
df = pd.read_csv(url)

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


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'])

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]')

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