Here is a sample logic on how to convert a string to a date in Python and the packages needed.
ON THIS PAGE
Get Current Date
The code below prints the current date.
from datetime import datetime
z = datetime.now()
print(z)
The output of the 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
Get only Date from the String
The below example shows how to use srptime() and date() methods to get only the Date from the input string.
from datetime import datetime
text = '2014-08-13'
y = datetime.strptime(text, '%Y-%m-%d').date()
print(y)
The strptime() method converts the string to date.
2014-08-13
** Process exited - Return Code: 0 **
Press Enter to exit terminal
Get difference between Dates
Now you can write a Python program to find the 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 the difference between the two dates.
Date difference: 3048 days, 12:30:42.835745
** Process exited - Return Code: 0 **
Press Enter to exit terminal
Related






