I'm trying to build a simple currency converter tool that uses the Frankfurter API. However, the available range of dates for the API is limited to after 4th of January 1999. I am wondering, with my current block of code, how I can limit the range of dates so that it returns a prompt for the user to input something after the 4th of January 1999, if they pick a date before 4th of January 1999.
My code (as per below) asks the user for input. Then it'll convert the string with the datetime module. However, I'm finding it hard to set the range above, as well as under which statement (while, except, try, etc.) to put it. Appreciate your help and thanks so much!
while True:
rate_date = str(input("Enter the date you'd like the exchange rate to be on (yyyy-mm-dd): "))
try:
str_to_date = datetime.strptime(rate_date, '%Y-%m-%d').date()
except ValueError as e:
print("Error: {}".format(e), end = '\n')
print("Please enter a suitable date in the required format.")
except:
print("Please enter a suitable date in the required format.")
else:
break```
CodePudding user response:
You could try prequalifying with an if statement
import datetime
raw_date = datetime.date(year, month, day)
minDate = datetime.date(1999, 1, 4)
if raw_date > minDate:
while True:
rate_date = str(input("Enter the date you'd like the exchange rate to be on (yyyy-mm-dd): "))
try:
str_to_date = datetime.strptime(rate_date, '%Y-%m-%d').date()
except ValueError as e:
print("Error: {}".format(e), end = '\n')
print("Please enter a suitable date in the required format.")
except:
print("Please enter a suitable date in the required format.")
else:
break
else:
print 'Enter a date greater than 1999, 01, 04'
CodePudding user response:
Was able to use this:
while True:
rate_date = str(input("Enter the date you'd like the exchange rate to be on (yyyy-mm-dd): "))
try:
str_to_date = datetime.strptime(rate_date, '%Y-%m-%d').date()
except ValueError as e:
print("Error: {}".format(e), end = '\n')
print("Please enter a suitable date in the required format.")
except:
print("Please enter a suitable date in the required format.")
else:
if str_to_date < date(1999, 1, 4) or str_to_date > date.today():
print("The date entered is outside the range of dates available. \nPlease enter a date between 1999-01-04 and today, {}.".format(date.today()))
continue
else:
break
Thanks to everyone above!