This article covers the two most popular ways to convert a column to DateTime in pandas.

1. By Using pd.to_datetime() function

Syntax:

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

The syntax can be demonstrated using an example in Python:

# importing pandas to work with data
import pandas as pd 
  
# Creating a dataframe 
df = pd.DataFrame({'Date':['01/01/2020', '10/01/2020', '20/01/2020'], 
                'Expenses':[5000, 1000, 1500]}) 
  
# printing the datatype of the dataframe's columns
df.info() 
pandas datetime

As we can see the “Date” column is an object column. Now, converting it into datetime by using pd.to_datetime() function.

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

# printing the datatype of the dataframe's columns
df.info() 
pandas datetime

2. By Using df.astype() function

Syntax:

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

The syntax can be demonstrated using an example in Python:

# importing pandas to work with data
import pandas as pd 
  
# Creating a dataframe 
df = pd.DataFrame({'Date':['01/01/2020', '10/01/2020', '20/01/2020'], 
                'Expenses':[5000, 1000, 1500]}) 
  
# printing the datatype of the dataframe's columns
df.info() 
pandas datetime

As we can see the “Date” column is an object column. Now, converting it into datetime by using df.astype() function.

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

# printing the datatype of the dataframe's columns
df.info() 
pandas datetime

In Conclusion:

This is how you convert a column to datetime in Pandas. Also, learn how to convert a column to string in pandas.

LEAVE A REPLY

Please enter your comment!
Please enter your name here