以下是一个示例代码,演示如何按日期过滤数据库表:
import sqlite3
from datetime import datetime
# 连接到 SQLite 数据库
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# 创建一个包含日期的数据库表
cursor.execute('''CREATE TABLE IF NOT EXISTS mytable
(id INTEGER PRIMARY KEY, name TEXT, date TEXT)''')
# 插入一些示例数据
cursor.execute("INSERT INTO mytable (name, date) VALUES (?, ?)", ("John", "2021-01-01"))
cursor.execute("INSERT INTO mytable (name, date) VALUES (?, ?)", ("Jane", "2021-02-15"))
cursor.execute("INSERT INTO mytable (name, date) VALUES (?, ?)", ("Bob", "2021-03-30"))
# 提交更改并关闭连接
conn.commit()
conn.close()
# 连接到 SQLite 数据库
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# 获取当前日期
current_date = datetime.now().date()
# 按日期过滤数据库表
cursor.execute("SELECT * FROM mytable WHERE date <= ?", (current_date,))
# 获取结果并打印
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭连接
conn.close()
上述代码示例使用 SQLite 数据库,并创建了一个名为 mytable 的数据库表,包含 id,name 和 date 列。代码插入了一些示例数据,并使用 SELECT 查询按日期过滤数据库表。最后,打印了符合条件的行。
请注意,这只是一个示例,实际情况下,你可能需要根据你使用的数据库管理系统和编程语言进行适当的调整。
上一篇:按日期过滤pandas数据帧以计算节目时间线上的观看次数
下一篇:按日期过滤数组