How to Create a Simple Program for Date Validation and Increment Using Python Looping?
Share
Condition for Simple Program for Date Validation and Increment in Python
Description: The program provided is designed to continuously accept a date input from the user, validate whether it is a correct date in the format YYYY-MM-DD, and increment the date by one day if valid. It runs in a loop, allowing multiple inputs until the user chooses to exit.
Step-by-Step Process
User Input: The program prompts the user to enter a date in the format YYYY-MM-DD or type "exit" to quit the program.
Date Validation: It checks if the entered date is valid by attempting to parse it using datetime.strptime(). If the date is invalid (e.g., "2024-02-30"), an error message is shown.
Date Incrementing: If the date is valid, the program converts the string to a datetime object and increments the date by one day using timedelta(days=1).
Display Results: The program prints the original valid date and the incremented (next day) date.
Looping or Exit: The program continues to loop, allowing the user to input new dates or type "exit" to stop the program.
Sample Code
from datetime import datetime, timedelta
# Function to validate date
def is_valid_date(date_str):
try:
# Try to parse the date string to a datetime object
datetime.strptime(date_str, "%Y-%m-%d")
return True
except ValueError:
return False
# Function to increment date by 1 day
def increment_date(date_str):
# Convert the date string to a datetime object
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
# Increment the date by one day
incremented_date = date_obj + timedelta(days=1)
# Return the incremented date as a string
return incremented_date.strftime("%Y-%m-%d")
# Main program with loop
while True:
date_input = input("Enter a date (YYYY-MM-DD) or 'exit' to quit: ")
if date_input.lower() == 'exit':
print("Exiting the program.")
break
if is_valid_date(date_input):
print(f"Original Date: {date_input}")
incremented_date = increment_date(date_input)
print(f"Incremented Date: {incremented_date}")
else:
print("Invalid date format. Please enter the date in YYYY-MM-DD format.")