Python Program to Check if a Date is Valid and Print the Incremented Date if it is


When it is required to check if a date is valid or not, and print the incremented date if it is a valid date, the ‘if’ condition is used.

Below is a demonstration of the same −

Example

 Live Demo

my_date = input("Enter a date : ")
dd,mm,yy = my_date.split('/')
dd=int(dd)
mm=int(mm)
yy=int(yy)
if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12):
   max_val = 31
elif(mm==4 or mm==6 or mm==9 or mm==11):
   max_val = 30
elif(yy%4==0 and yy%100!=0 or yy%400==0):
   max_val = 29
else:
   max_val = 28
if(mm<1 or mm>12 or dd<1 or dd> max_val):
   print("The date is invalid")
elif(dd==max_val and mm!=12):
   dd=1
   mm=mm+1
   print("The incremented date is : ",dd,mm,yy)
elif(dd==31 and mm==12):
   dd=1
   mm=1
   yy=yy+1
   print("The incremented date is : ",dd,mm,yy)
else:
   dd=dd+1
   print("The incremented date is : ",dd,mm,yy)

Output

Enter a date : 5/07/2021
The incremented date is : 6 7 2021

Explanation

  • The date is entered as user input.

  • It is split based on ‘/’ symbol.

  • The date, month and year are converted into integers.

  • An ‘if’ condition is specified to see if the month is even or odd.

  • Another ‘if’ condition is specified to check the year.

  • Based on the results of the ‘if’ condition, the month is incremented.

  • This is displayed on the console.

Updated on: 16-Apr-2021

307 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements