Search code examples
pythonfunctiondatetimeuser-input

Getting Date input from the user and passing as parameter using python


I have a query text file like,

Select * from emp WHERE empdate >= '%s';

I'm specifying the date and passing as a parameter inside the function using python, like

 DATE = "28-01-2019"

and I'm reading the query file and passing the DATE parameters to a function for pulling the data for the specified date.

So, I need to get the date input from the user and to pass that date for DATE variable and that should reflect on the query file.

SAMPLE: When the user enter the date as 09-02-2019 This should go inside the DATE and in the query file and the final output is to fetch the data for 09-02-2019.

Thank you


Solution

  • import re
    
    date_input = input("Enter date: ")
    while not re.match('\d{1,2}-\d{1,2}-\d{4}', date_input):
        date_input = input("Invalid date entered (dd-mm-yyyy), Enter date: ")
    
    query = f"Select * from emp WHERE empdate >= '{date_input}';"
    
    # Use your query wherever you need...
    

    NOTE: This regex just validate the structure of 'dd-mm-yyyy' but doesn't validate that the date value makes any sense. Because you fetch from a DB it's *probably* fine, but not necessarily. use it with caution.