You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用SQLAlchemy查询booking_date前2天的预订并解决1292报错

错误原因
  • 你错误地将SQLAlchemy的BookingInfo.booking_date列对象当成了Python原生日期对象操作:直接调用strftime方法、和timedelta做算术运算,会生成数据库无法识别的非法SQL表达式,最终触发1292日期截断错误。
  • 对数据库存储的日期字段做运算,不要提前在Python层做格式转换,应该优先用ORM原生语法或者数据库日期函数实现。
正确实现代码

根据你的需求分两种常用场景:

场景1:查询**booking_date等于「指定日期往前推2天」**的记录

比如要查比今天早2天的所有预订,直接在Python层计算出目标日期再过滤即可:

from datetime import date, timedelta

# 计算目标日期(如果指定日期不是今天,把date.today()替换成你的指定日期即可)
target_date = date.today() - timedelta(days=2)
# ORM查询
records = self._query(BookingInfo).filter(BookingInfo.booking_date == target_date).all()

场景2:需要在SQL层对booking_date字段做减2天运算后再过滤

比如要查询所有booking_date往前推2天后等于某个指定日期的记录,用SQLAlchemy内置函数实现:

from datetime import date
from sqlalchemy import func

target_date = date.today() # 替换成你需要对比的日期
records = self._query(BookingInfo).filter(
    func.date_sub(BookingInfo.booking_date, func.interval(2, 'DAY')) == target_date
).all()

内容的提问来源于stack exchange,提问作者Mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 23:57:04