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.
1 2 3 4 5 6 7 8 |
# importing the datetime library import datetime # Generating dates using various string input formats print(datetime.datetime.strptime('22-April-2020', '%d-%B-%Y')) print(datetime.datetime.strptime('22-04-2020', '%d-%m-%Y')) print(datetime.datetime.strptime('04/22/2020', '%m/%d/%Y')) print(datetime.datetime.strptime('Mar/22/2020', '%b/%d/%Y')) |
Sample Output:

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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Defining Department Data import pandas as pd DepartmentData=pd.DataFrame({'Dep': ['BI','QA','DEV'], 'id': [101,102,103], 'DOJ': ['12-Mar-2020','2-Feb-2020','15-Jan-2020'] }) # Priting data print(DepartmentData) # Defining a Function to convert a string to date def CreateDate(InpString): import datetime return(datetime.datetime.strptime(InpString, '%d-%b-%Y')) # Creating the Joining Date DepartmentData['JoiningDate']=DepartmentData['DOJ'].apply(CreateDate) print(DepartmentData) print('###'*15) DepartmentData.info() |
Sample Output:

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!