Instead of converting this_year to a string, just leave it as a datetime.date object:
this_year = DT.date(DT.date.today().year,1,1)
import sqlite3 import datetime as DT this_year = (DT.date(DT.date.today().isocalendar()[0], 1, 1)) # this_year = ("'"+str(this_year)+"'") # this_year = DT.date(DT.date.today().year,1,1) with sqlite3.connect(':memory:') as conn: cursor = conn.cursor() sql = '''CREATE TABLE TEST_TABLE ("ID" TEXT, "DATE_IN" DATE, "WEEK_IN" number) ''' cursor.execute(sql) sql = 'INSERT INTO TEST_TABLE(ID, DATE_IN, WEEK_IN) VALUES (?,?,?)' cursor.executemany(sql, [[1,'2012-03-25',13],[2,'2013-03-25',13],]) sql = 'SELECT ID FROM TEST_TABLE where WEEK_IN = 13 and DATE_IN > ?' cursor.execute(sql, [this_year]) for row in cursor: print(row)
gives
(u'2',)
The sqlite3 database adapter will provide arguments for you when you write parameterized SQL and use a form with two cursor.execute arguments. Therefore, you do not need (or do not want) to give arguments manually yourself.
So
this_year = str(this_year)
instead
this_year = ("'"+str(this_year)+"'")
also works, but as shown above, both rows are not needed since sqlite3 will accept datetime objects as arguments.
also works.
Since sqlite3 automatically quotes arguments when you manually add quotes, the last argument gets two sets of quotes. SQL finishes comparison
In [59]: '2012-03-25' > "'2013-01-01'" Out[59]: True
therefore, both rows were erroneously returned.