How to Convert String to Date in Python

Here’s how you can convert string to date in python. What we call a string in python, which encloses in quotes.

Below you’ll find sample logic on how to convert string to date in python and the packages needed.

Convert String to date

The code below prints current date.

from datetime import datetime
z = datetime.now()
print(z)

The output of current date is in the format of YYYY-MM-DD.

2022-12-17 12:23:28.518007
** Process exited - Return Code: 0 **
Press Enter to exit terminal

Strptime method

Here’s an example that converts string to date without time. The srptime method takes two arguments of string and format.

from datetime import datetime
text = '2014-08-13'
y = datetime.strptime(text, '%Y-%m-%d')
print(y)

The strptime() method converts the string to date.

2014-08-13 00:00:00
** Process exited - Return Code: 0 **
Press Enter to exit terminal

Now you can write python program to find difference between two dates.

from datetime import datetime
text = '2014-08-13'
y = datetime.strptime(text, '%Y-%m-%d')
z = datetime.now()
diff = z - y
print('Date difference:',diff)

Here’s the output that gives difference between the two dates.

Date difference: 3048 days, 12:30:42.835745
** Process exited - Return Code: 0 **
Press Enter to exit terminal

Related

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.