Home > other >  python code to check if a date is valid and increment the date
python code to check if a date is valid and increment the date

Time:12-06

The code should check if the entered date is valid or not. If the date is valid then print "the date is valid" and if is not, then print "the date is invalid". If the date is invalid then it shouldn't increment the date. so the below code prints if the code is invalid, but doesn't print if the code is valid. The whole code works perfectly, but I want to add a part where is says "the date is valid" if it actually is.

date=input("Enter the date: ")
dd,mm,yy=date.split('/')
dd=int(dd)
mm=int(mm)
yy=int(yy)

if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12):
    max1=31

elif(mm==4 or mm==6 or mm==9 or mm==11):
    max1=30

elif(yy%4==0 and yy%100!=0 or yy%400==0):
    max1=29
else:
    max1=28


if(mm<1 or mm>12 or dd<1 or dd>max1):
    print("Date is invalid.")



elif(dd==max1 and mm!=12):
    dd=1
    mm=mm 1
    print("The incremented date is: ",dd,mm,yy)

elif(dd==31 and mm==12):
    dd=1
    mm=1
    yy=yy 1
    print("The incremented date is: ",dd,mm,yy)

else:
    dd=dd 1
    print("The incremented date is: ",dd,mm,yy)

CodePudding user response:

add one more elif

elif(mm>=1 or mm<=12 or dd>=1 or dd<=max1):
    print("Date is valid.")

CodePudding user response:

Staying as close as possible to your original code, we can try:

def date_checker(date):
    dd,mm,yy=date.split('/')
    dd=int(dd)
    mm=int(mm)
    yy=int(yy)
    
    # Max days based on month value
    if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12):
        max1=31
    elif(mm==4 or mm==6 or mm==9 or mm==11):
        max1=30
    elif(yy%4==0 and yy%100!=0 or yy%400==0):
        max1=29
    else:
        max1=28
    
    # Check month and day vals for validity
    if(mm<1 or mm>12 or dd<1 or dd>max1):
        print("Date is invalid.")
    else:
        print("Date is valid")
    # Iterate:
        if(dd==max1 and mm!=12):
            dd=1
            mm=mm 1
            print("The incremented date is: ",dd,"/",mm,"/",yy)
        elif(dd==31 and mm==12):
            dd=1
            mm=1
            yy=yy 1
            print("The incremented date is: ",dd,"/",mm,"/",yy)
        else:
            dd=dd 1
            print("The incremented date is: ",dd,"/",mm,"/",yy)
    
date = input("Enter the date: ")
date_checker(date)

A simpler approach might be to use the datetime package:

from datetime import datetime,timedelta

date = input("Enter the date: ")
try:
    date = datetime.strptime(date,"%d/%m/%Y")
    print("Date is valid.")
    print("The incremented date is: ",datetime.strftime(date   timedelta(days=1), format = "%d/%m/%Y"))
except ValueError:
    print("Date is invalid.")

Then the incremented date automatically wraps around months and years, and there's no need for so many if/else statements.

  • Related