Validate Gregorian Date in python


Write a Python program to validate a Gregorian date. The month is between 1 and 12 inclusive, the day is within the allowed number of days for the given month. Leap year’s are taken into consideration. The year is between 1 and 32767 inclusive


This program is a simple Python script that is checking if a date is valid or not. It starts by defining the values for the month (m), day (d), and year (y) as integers. Then, it uses a try-except block to handle any possible errors that might occur during the date validation process.

  • The line m, d, y = map(int, (m, d, y)) is converting the values of m, d, y to integers, just in case they were not already defined as integers.
  • The line datetime.date(y, m, d) creates a date object using the year (y), month (m), and day (d) values that were defined earlier. The datetime module is a built-in Python module that provides classes for working with dates and times. The date class is used here to create a date object that represents a particular date.
  • If the date is valid, the code inside the try block will be executed, and the result True will be printed. If the date is not valid, a ValueError exception will be raised, and the code inside the except block will be executed, printing False.
  • The ValueError exception is raised by the datetime.date method when the date is not valid, for example, if the month value is greater than 12, or if the day value is greater than the number of days in the month. This exception is then caught by the except block, and the result False is printed.

Source Code

import datetime
m, d, y = 11, 11, 2002
try:
	m, d, y = map(int, (m, d, y))
	datetime.date(y, m, d)
	print(True)
except ValueError:
	print(False)

Output

True

Example Programs