Python Pandas - Convert string data into datetime type

PythonServer Side ProgrammingProgramming

To convert string data to actual dates i.e. datetime type, use the to_datetime() method. At first, let us create a DataFrame with 3 categories, one of the them is a date string −

dataFrame = pd.DataFrame({
   'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Chairs'],'Date_of_Purchase': ['10/07/2021','20/04/2021','25/06/2021','15/02/2021'],
})

Convert date strings to actual dates using to_datetime() −

dataFrame['Date_of_Purchase'] = pd.to_datetime(dataFrame['Date_of_Purchase'])

Example

Following is the complete code −

import pandas as pd

# create a dataframe
dataFrame = pd.DataFrame({
   'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Chairs'],'Date_of_Purchase': ['10/07/2021','20/04/2021','25/06/2021','15/02/2021'],
})

print"
DataFrame...
",dataFrame # convert date strings to actual dates dataFrame['Date_of_Purchase'] = pd.to_datetime(dataFrame['Date_of_Purchase']) print"
Updated DataFrame (string dates converted to dates)...
",dataFrame

Output

This will produce the following output −

DataFrame...
   Date_of_Purchase   Product Category   Product Name
0       10/07/2021            Computer      Keyboard
1       20/04/2021        Mobile Phone       Charger
2       25/06/2021         Electronics       SmartTV
3       15/02/2021          Stationery        Chairs

Updated DataFrame (string dates converted to dates)...
   Date_of_Purchase   Product Category   Product Name
0       2021-10-07           Computer       Keyboard
1       2021-04-20       Mobile Phone        Charger
2       2021-06-25        Electronics        SmartTV
3       2021-02-15         Stationery         Chairs
raja
Updated on 16-Sep-2021 06:59:02

Advertisements