我正在尝试对带有基于日期的where子句的选择查询使用sqlalchemy,但是在查询语句中未解析日期。有什么建议吗?
一些进口。
import sqlalchemy as sq
from datetime import datetime
连接到数据库并提取表信息...
# Connect to the database
engine = sq.create_engine('sqlite:///C:/Blah/Blah/sqlite_file.db')
metadata = sq.MetaData(engine)
# Access the table.
table = sq.Table('customers', metadata, autoload=True, autoload_with=engine)
print(repr(customer_table))
Table('customers', MetaData(bind=Engine(sqlite:///C:/Blah/Blah/sqlite_file.db)),
Column('customer_id', BIGINT(), table=<customers>),
Column('cluster_num', INTEGER(), table=<customers>),
Column('product', TEXT(), table=<customers>),
Column('start_month', DATE(), table=<customers>)), schema=None)
因此,我们看到“ start_month”列记录为日期。有关信息,表中的每个日期都是相应月份的第一天。
将我感兴趣的帐户开设日期定义为字符串和datetime.datetime对象...
date_str = '2015-01-01'
date_dt = datetime.strptime(date_str, '%Y-%m-%d')
首先使用sql编写查询,然后尝试两次sqlalchemy。
q = "SELECT customer_id, product FROM customers WHERE start_month = '{}'".format(date_str)
stmt = sq.select([table.columns.customer_id, table.columns.product])
stmt_str = stmt.where(table.columns.start_month == date_str)
stmt_dt = stmt.where(table.columns.start_month == date_dt)
SQL有效。
print(q)
SELECT customer_id, product FROM customers WHERE start_month = '2015-01-01'
但是这两个sqlalchemy方法都不起作用。
print(stmt_str)
SELECT customers.customer_id, customers.product
FROM customers
WHERE customers.start_month = ?
print(stmt_dt)
SELECT customers.customer_id, customers.product
FROM customers
WHERE customers.start_month = ?
如您所见,日期被解析为“?”而不是我想要的日期。
现在我可以使用sql字符串方法了,但是没有人解释为什么我不能使用sqlalchemy语法在where子句中指定日期吗?