Python Program to Check if a Date is Valid and Print the Incremented Date if it is

When it is required to check if a date is valid or not, and print the incremented date if it is a valid date, the 'if' condition is used along with date validation logic.

Below is a demonstration of the same ?

Example

my_date = input("Enter a date : ")
dd, mm, yy = my_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):
    max_val = 31
elif(mm == 4 or mm == 6 or mm == 9 or mm == 11):
    max_val = 30
elif(yy % 4 == 0 and yy % 100 != 0 or yy % 400 == 0):
    max_val = 29
else:
    max_val = 28

if(mm < 1 or mm > 12 or dd < 1 or dd > max_val):
    print("The date is invalid")
elif(dd == max_val 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)

Output

Enter a date : 5/07/2021
The incremented date is :  6 7 2021

How It Works

The program follows these steps:

  • The date is entered as user input in DD/MM/YYYY format.

  • It is split based on '/' symbol to extract day, month, and year.

  • The date, month and year are converted into integers.

  • The program determines the maximum days for the given month (31 for Jan, Mar, May, Jul, Aug, Oct, Dec; 30 for Apr, Jun, Sep, Nov; 28/29 for Feb based on leap year).

  • Date validation checks if the month is between 1-12 and day is within valid range.

  • If valid, the date is incremented by one day, handling month-end and year-end transitions.

  • The result is displayed on the console.

Alternative Approach Using datetime Module

from datetime import datetime, timedelta

try:
    date_input = input("Enter a date (DD/MM/YYYY): ")
    dd, mm, yy = map(int, date_input.split('/'))
    
    # Create datetime object to validate
    current_date = datetime(yy, mm, dd)
    
    # Increment by one day
    next_date = current_date + timedelta(days=1)
    
    print(f"The incremented date is: {next_date.strftime('%d/%m/%Y')}")
    
except ValueError:
    print("The date is invalid")

Output

Enter a date (DD/MM/YYYY): 5/07/2021
The incremented date is: 06/07/2021

Conclusion

The manual approach provides full control over date validation and increment logic. The datetime module approach is more concise and handles edge cases automatically, making it the preferred method for date operations.

Updated on: 2026-03-25T19:07:43+05:30

650 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements