Python: Validate a Gregorian date

Python Datetime: Exercise-53 with Solution

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.

Sample Solution:

Python Code:

import datetime
def check_date(m, d, y):
        m, d, y = map(int, (m, d, y))
        datetime.date(y, m, d)
        return True
    except ValueError:
        return False

print(check_date(11, 11, 2002))
print(check_date('11', '11', '2002'))
print(check_date(13, 11, 2002))

Sample Output:



Flowchart: Validate a Gregorian date.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to get the first and last second.
Next: Write a Python program to set the default timezone used by all date/time functions.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.