Home > database >  Replace multiple strings with python variable in a sql query
Replace multiple strings with python variable in a sql query

Time:04-18

I have a datetime list lets say datelist which I later convert into string. I want to run following sql query : select * from test_table_20220401 where date < '2022-04-01 00:00:00' and date1 > '20220401' for multiple dates. So I need to replace the 'dates' string in the query with python variables from the datelist that I have created. I can resolve for this when I have to replace a string from a query with only one python variable. Please refer the below code:

for in datelist:
    query = "select * from test_table where date1 > {}".format(i)

Please let me know. Thank you.

CodePudding user response:

It looks like date and date1 columns have different formats in test_table. If that's the case, then you'll need a function to convert the dates in datelist to the format required by the sql table.

In order to pass multiple vars into a string, I typically use f-strings.

date = '2022-04-01 00:00:00'
date1 = '20220401'

query = f'select * from test_table_20220401 where date < {date} and date1 > {date1}'

You can also add multiple variables with .format(). An answer here explains. Documentation for string formatting styles and .format() function specifically is here.

  • Related