In this tutorial, you will write a Python program to calculate the number of days between two dates.
If you are new to Python, to understand this code, you should first check:
- How to get basic input and output in Python
- If and else conditional statements in Python
- While loop in python
- Python Lists
Simple Code
while True:
try:
print('Enter date in the format : dd/mm/yy')
date1 = input('Enter the first date : ')
date2 = input('Enter the second date : ')
date_1 = date1.split('/')
date_2 = date2.split('/')
diff = (int(date_2[2]) * 365 + int(date_2[1]) * 30 + int(date_2[0])) - (int(date_1[2]) * 365 + int(date_1[1]) * 30 + int(date_1[0]))
print('The number of days between' , date2 , 'and' , date1 , 'is' , diff ,'days.')
break
except:
print('Follow the format and use digits only')
Output
Enter date in the format : dd/mm/yy
Enter the first date : 20/10/2010
Enter the second date : 20/10/2011
The number of days between 20/10/2011 and 20/10/2010 is 365 days.
Code with explanation
#program will run until it is executed successfully!
while True:
#This try block will be executed first and if the user enter the date in the right format, the result will be printed and program will end successfully
#But if the user enter input in wrong formate, program will throw an error and will run again
try:
#take input from the user
print('Enter date in the format : dd/mm/yy')
#get the first date
date1 = input('Enter the first date : ')
#get the second date
date2 = input('Enter the second date : ')
#split the entered date into date, month and year by using .split() method
#this split method will split the string into a list of number such as, 01/05/2010 will be converted to list ['01', '05', '2010']
date_1 = date1.split('/')
date_2 = date2.split('/')
print(date_2)
#calculating the difference between two dates by subtracting date 2 from date 1
diff = (int(date_2[2]) * 365 + int(date_2[1]) * 30 + int(date_2[0])) - (int(date_1[2]) * 365 + int(date_1[1]) * 30 + int(date_1[0]))
print('The number of days between' , date2 , 'and' , date1 , 'is' , diff ,'days.')
#this break command will end the program if it is executed successfully.
break
#But in some cases, the user may enter some alphabet or any other character. Then this error will be displayed and loop will run the program again
except:
print('Invalid Entry. Follow the format dd/mm/yy and use digits only.')
Output
Enter date in the format : dd/mm/yy
Enter the first date : 20-01-10
Enter the second date : 20-01-11
Invalid Entry. Follow the format dd/mm/yy and use digits only.t
Enter date in the format : dd/mm/yy
Enter the first date : 20/10/2010
Enter the second date : 20/10/2011
The number of days between 20/10/2011 and 20/10/2010 is 365 days.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.