I have a function that prompts the user for a date in the future and checks if that date is on a weekday. If the date is not on a weekday, the function is called again to get new input from the user. The code works only for one month in the future. For example, since the current month is July, the function would not be called again if the user inputted the date of a Saturday at the end of August.
Is there a way to fix this problem or a better function to use other than datetime.weekday()
?
def appointment_date():
'''
Prompts the user for the day of his appointment until he has a date that is in the future (not current day) and on a weekday.
'''
app_date = validator("On what day would you like to schedule your appointment? ", r"^[01]?[0-9]/[0-3]?[0-9]/[12][09][0-9][0-9]?$")
month, day, year = app_date.split("/")
this_year = datetime.datetime.today().year
this_month = datetime.datetime.today().month
today = datetime.datetime.today().day
if int(year) < int(this_year):
appointment_date()
#other code here checks if the date is in the future
else:
day_instance = datetime.datetime(int(year), int(month), int(day))
weekday = day_instance.weekday()
if weekday < 0 or weekday > 4:
print("Needs to be on a weekday.")
appointment_date()
You can use isoweekday
function, which treats Monday as the first day of the week, and weekdays range from 1 to 7 (both inclusive). Also, instead of separating day, month and year and doing the individual comparison, you can simply compare datetime objects, for a cleaner code.
import datetime
def appointment_date():
'''
Prompts the user for the day of his appointment until he has a date that is in the future (not current day) and on a weekday.
'''
app_date = validator("On what day would you like to schedule your appointment? ", r"^[01]?[0-9]/[0-3]?[0-9]/[12][09][0-9][0-9]?$")
appointed_day = datetime.datetime.strptime(app_date, '%m/%d/%Y')
if appointed_day <= datetime.datetime.today():
print('appointment_date can\'t be in past')
appointment_date()
#other code here checks if the date is in the future
else:
if appointed_day.isoweekday() > 5:
print("Needs to be on a weekday.")
appointment_date()