Govind Chandak Govind Chandak - 6 months ago 17
Python Question

Date Validity and Leap Year Checker

I've been trying to find ways to shorten or modify this code to increase the efficiency and reduce the complexity. Any Help?

I'm new to this website so I hope for a good response :D!

a=int(input('Enter the date:'))
b=int(input('Enter the month:'))
c=int(input('Enter the year:'))
if b<=12 and a<=31 and b>0 and a>0:
if b==2:
if a>29:
k=0
elif a<=29:
k=1
elif b==1 or b==3 or b==5 or b==7 or b==8 or b==10 or b==12:
if b>31:
k=0
else:
k=1
else:
if b>30:
k=0
else:
k=1
else:
k=0

if k==0:
print 'Invalid Date'

elif k==1:
if (c%4)==0:
if (c%100)==0:
if (c%400)==0:
t=1
else:
t=0
else:
t=1

if t==1:
print 'It is a leap year and has a valid date'
elif t==0 :
if a==29 and b==2:
print 'It isn\'t a valid date neither a leap year'
else:
print 'It is a valid date and a leap year'

Answer

Use inbuilt modules -

import datetime
import calendar


def validate_date(year, month, date):
    """Returns True if valid date else False"""
    try:
        datetime.datetime(year, month, date)
        return True
    except ValueError:
        return False

Use calender.isleap(year) to check if the year is a leap year or not.

Comments