Home > Software engineering >  How to select dates in SQLite with python
How to select dates in SQLite with python

Time:09-21

Im trying to query a table, and need to grab all products that have a date = today date. Below is my code so far

import sqlite3
from datetime import date

date = date.today()
con = sqlite3.connect('test.db')
cur = con.cursor()

date = date.today()

sql_q = f'''SELECT date, name FROM table WHERE date = {date}'''

table = cur.execute(sql_q)

for row in table:
    print(row)

i am using an SQlite 3 db and all data has been entered with the following format: 2022-09-20

However this variable type does not seem to work with SQL. i know the SQL code should look somthing like this

SELECT name FROM test WHERE date = '2022-09-20'

but i'd like the date to be selected automatically from python rather than typing it in manually.

CodePudding user response:

Use the function date() to get the current date:

SELECT name FROM test WHERE date = date()

or CURRENT_DATE:

SELECT name FROM test WHERE date = CURRENT_DATE

CodePudding user response:

I think you need to convert date to string and then pass it in query. maybe your datatype of column and date.today() is different.

date = date.strftime('%Y-%m-%d')

try using this.

  • Related