How to convert string to date in Python

Dates are special datatype. The values look like strings but it has properties like finding the number of days difference between two dates, checking if a date is greater than others or not, etc.

The popular library which is used for dates manipulation in Python is datetime.

strptime() function from the datetime library is used to convert a string input as a date. Below code snippet shows the different formats which are commonly used.

All you have to do is identify the sequencing of the day month and year in the input string and provide that format.

Sample Output:

Converting strings to date


Convert a string column to date column in a pandas data frame

If there is a column having date values in string format, then we can convert it into a date format by creating a user-defined function and applying it to each value in that column.

Below snippet shows how to take input of a string value and convert it into a date.

Sample Output:

Changing a string column to date column in pandas data frame
Changing a string column to date column in a pandas data frame

If you look at the data type of the JoiningDate Column it is a date, while the data type of the original column DOJ is a string!

Author Details
Lead Data Scientist
Farukh is an innovator in solving industry problems using Artificial intelligence. His expertise is backed with 10 years of industry experience. Being a senior data scientist he is responsible for designing the AI/ML solution to provide maximum gains for the clients. As a thought leader, his focus is on solving the key business problems of the CPG Industry. He has worked across different domains like Telecom, Insurance, and Logistics. He has worked with global tech leaders including Infosys, IBM, and Persistent systems. His passion to teach inspired him to create this website!

Leave a Reply!

Your email address will not be published. Required fields are marked *