简体   繁体   English

SQLite 查询 Python 使用 DATETIME 和变量未按预期工作

[英]SQLite query in Python using DATETIME and variables not working as expected

I'm trying to query a database using Python/Pandas.我正在尝试使用 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.这将是一个反复出现的请求,我想回顾一下随时间变化的时间 window,所以我想在我如何做到这一点时使用一些智慧。

In my SQLite query, if I say在我的 SQLite 查询中,如果我说

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.我发现 endDate 变量确实有效,但 startDate 没有。 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).由于结果是空的,就好像它正在查看DATETIME(\'now\')而没有看到'-6 month'位(现在与现在比较,这将是空的)。 Any ideas how I can pass this through to the query correctly using Python?有什么想法可以使用 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])

When you provide parameters to a query, they're treated as literals, not expressions that SQL should evaluate.当您向查询提供参数时,它们被视为文字,而不是 SQL 应评估的表达式。

You can pass the function arguments rather than the function as a string.您可以将 function arguments 而不是 function 作为字符串传递。

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])

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM