Python 中的 SQLite3 查询以检索两个日期之间的行数

SQLite3 Query in Python to Retrieve count of rows between two Dates

问题

我有一个带有两个 tables、bt 和数据的 sqlite3 数据库。 两个 table 都包含格式为 YYYY-MM-DD 的日期列。 我读过一篇 table 作为 pandas df.

我需要遍历 df 中的行和 return 该行日期后 14 天内的行数。

我试过的代码

import sqlite3 as lite
import pandas as pd

#Function to Create DB Connection and Raise Error
def create_connection(db_file):
    """ create a database connection to the SQLite database
        specified by db_file
    :param db_file: database file
    :return: Connection object or None
    """
    conn = None
    try:
        conn = lite.connect(db_file)
        return conn
    except lite.Error as e:
        print(e)

    return conn

#Creat Connection to DB and Create df
conn = create_connection('test.db')
df = pd.read_sql("Select * from data;", conn)

#Create Cursor
cur = conn.cursor()

#Iterate over rows in df and return count of rows within date range
for index ,row in df.iterrows():
    cur.execute("SELECT count(*) FROM bt WHERE id='{}' AND datetime(btdate) BETWEEN datetime('{}') AND datetime('{}', '-15 day');".format(row['id'], row['date'], row['date']))
    print(cur.fetchall())

当前输出

上面的查询 return 全部为 0,但是我知道 table.

中有符合此条件的行
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]
[(0,)]

期望输出 我想要的输出是两个日期之间的行数。

您的代码存在问题,您将运算符 BETWEEN 的起始值和结束值设置反了。
应该是:

BETWEEN datetime('{}', '-15 day') AND datetime('{}') 

但是,我也建议使用 ? 占位符来传递参数。
此外,如果日期已经采用 YYYYY-MM-DD.

格式,则无需使用 datetime()date() 函数来获取日期

使用这个:

sql = "SELECT COUNT(*) FROM bt WHERE id = ? AND btdate BETWEEN date(?, '-15 day') AND ?;"
cur.execute(sql, (row['id'], row['date'], row['date']))