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):
try:
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:
True True False
Flowchart:

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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join