0

Using Sqlite3 and Python, I want to able to get data between two dates with the dates as a variable. For example

date1 = 2020-10-16
date2 = 2020-10-18

"SELECT SUM (total) FROM table WHERE date BETWEEN '%"+date1+"%' AND '%"+date2+"%'"

How can I have BETWEEN grab the date in the variables. When I run this and print the query, the sum is 0 even though I place values inside the rows in (total)

1 Answers1

2

Your variables should be strings:

date1 = "2020-10-16"
date2 = "2020-10-18"

because a variable like:

date1 = 2020-10-16

is evaluated as 1994 = 2020 - 10 -16.

You should use ? placeholders in your query for the 2 date parameters:

query = "SELECT SUM(total) AS total FROM tablename WHERE date BETWEEN ? AND ?"

and pass the parameters when you execute the query:

curs.execute(query, (date1, date2)) 
forpas
  • 160,666
  • 10
  • 38
  • 76