Python Program to Check if a Date is Valid or not

In this example, we will write a python program to take input date from the user and display whether it is valid or not. To better understand this example, make sure you have knowledge of the following tutorials:-

Let us have basic information about the valid dates:-

  • The month should be a number from 1 to 12
  • The maximum day in a month is fixed as
    • January, March, May, July,  August, October, December has 31 days
    • April, June, September, November has 30 days
    • February has 28 days (29 in leap years)
  • Leap year calculation is required to check the number of days for February

Python Program to Check if a Date is Valid or not

year = int(input("Enter year: "))
month = int(input("Enter month: "))
day = int(input("Enter day: "))

# Get Max value for a day in given month
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
    max_day_value = 31
elif month == 4 or month == 6 or month == 9 or month == 11:
    max_day_value = 30
elif year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
    max_day_value = 29
else:
    max_day_value = 28

if month < 1 or month > 12:
    print("Date is invalid.")
elif day < 1 or day > max_day_value:
    print("Date is invalid.")
else:
    print("Valid Date")

The output of the above program is:-

Enter year: 1990
Enter month: 03
Enter day: 09
Valid Date
SHARE Python Program to Check if a Date is Valid or not

You may also like...

Leave a Reply

Your email address will not be published.

Share