Q:

Python program to check the given Date is valid or not

belongs to collection: Python basic programs

0

The datetime module

datetime module is an inbuilt module in Python which provides us to solve various problems related to date and time.

The basic syntax of try-except statement:

    try:
        #statement
    except:
        #statement
  • If the code or statement provided in the try block has no exception then only try executed.
  • If any exception occurs in the block of try then try block skipped and except block will be executed.

Algorithm to solve this problem:

  1. Initially, we will include the datetime module by using the import function.
  2. Take the date in the form of the date, month, year.
  3. Since we know that, we going to check the date is valid or not and if the date is valid then ok but when it's invalid, we will ValueError. So, here we will use the try-except statement.
  4. If the try statement has no exception then we will print the given date is valid otherwise we will print the given date is invalid.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Let's see the implementation of the above algorithm in the Python program.

import datetime 

d,m,y=map(int,input("Enter date: ").split())

try:
	s=datetime.date(y,m,d)
	print("Date is valid.")
except ValueError: 
	print("Date is invalid.")

Output

RUN 1:
Enter date: 10 10 2010
Date is valid.

RUN2:
Enter date: 30 2 2019
Date is invalid.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to print the calendar of any year... >>
<< Find the root of the quadratic equation in Python...