Setting datetime range for user input in Python

Question:

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```
Asked By: Kuchai913

||

Answers:

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'
Answered By: Justin Edwards

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!

Answered By: Kuchai913
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.