Convert DataFrame Column Type from String to Datetime

In this tutorial, we will learn how to convert DataFrame column type from string to datetime in Python Pandas? By Pranit Sharma Last updated : April 19, 2023

Overview

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consists of rows, columns, and the data. The Data inside the DataFrame can be of any type. Here, we will learn how to convert data in string format into DateTime format.

How to Convert DataFrame Column Type from String to Datetime?

To convert column type from string to datetime, you can simply use pandas.to_datetime() method, pass the DataFrame's column name for which you want to convert the type.

Syntax

Use the following syntax to convert the column type to datetime:

pd.to_datetime(df['column'])

Let us understand with the help of an example.

Python Program to Convert DataFrame Column Type from String to Datetime

# Importing pandas package
import pandas as pd

# Creating a Dictionary
dict = {'Name':['Amit','Bhairav','Chirag','Divyansh','Esha'],
        'DOB':['07/12/2001','08/11/2002','09/10/2003','10/09/2004','11/08/2005'],
        'Gender':['Male','Male','Male','Male','Female']}

# Creating a DataFrame
df = pd.DataFrame(dict)

# Checking datatype of column DOB
print(df.info())

# Converting the column DOB value into datatime format
df['DOB']= pd.to_datetime(df['DOB'])

# Checkig format of each column
print(df.info())

Output

At first the datatype of each column is object:

Output | string to datetime (1)

After converting the format of DOB column, the datatype has been converted to datetime format.

Output | string to datetime (2)

Python Pandas Programs »

All Python Pandas Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.