 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Pandas - Convert string data into datetime type
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"\nDataFrame...\n",dataFrame # convert date strings to actual dates dataFrame['Date_of_Purchase'] = pd.to_datetime(dataFrame['Date_of_Purchase']) print"\nUpdated DataFrame (string dates converted to dates)...\n",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
Advertisements
 