Home > other >  SQLite query in Python using DATETIME and variables not working as expected
SQLite query in Python using DATETIME and variables not working as expected

Time:12-15

I'm trying to query a database using Python/Pandas. This will be a recurring request where I'd like to look back into a window of time that changes over time, so I'd like to use some smarts in how I do this.

In my SQLite query, if I say

WHERE table.date BETWEEN DATETIME('now', '-6 month') AND DATETIME('now')

I get the result I expect. But if I try to move those to variables, the resulting table comes up empty. I found out that the endDate variable does work but the startDate does not. Presumably I'm doing something wrong with the escapes around the apostrophes? Since the result is coming up empty it's like it's looking at DATETIME(\'now\') and not seeing the '-6 month' bit (comparing now vs. now which would be empty). Any ideas how I can pass this through to the query correctly using Python?

startDate = 'DATETIME(\'now\', \'-6 month\')'
endDate = 'DATETIME(\'now\')'
query = '''
SELECT some stuff
FROM table
WHERE table.date BETWEEN ? AND ?
'''
df = pd.read_sql_query(query, db, params=[startDate, endDate])

CodePudding user response:

You can try with the string format as shown below,

startDate = "DATETIME('now', '-6 month')"
endDate = "DATETIME('now')"
query = '''
SELECT some stuff
FROM table
WHERE table.date BETWEEN {start_date} AND {end_data}
'''
df = pd.read_sql_query(query.format(start_date=startDate, end_data=endDate), db)

CodePudding user response:

When you provide parameters to a query, they're treated as literals, not expressions that SQL should evaluate.

You can pass the function arguments rather than the function as a string.

startDate = 'now'
startOffset = '-6 month'
endDate = 'now'
endOffset = ' 0 seconds'
query = '''
SELECT some stuff
FROM table
WHERE table.date BETWEEN DATETIME(?, ?) AND DATETIME(?, ?)
'''
df = pd.read_sql_query(query, db, params=[startDate, startOffset, endDate, endOffset])
  • Related