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

如何用SQLAlchemy筛选PostgreSQL中不在时间区间内的数据

在SQLAlchemy中筛选PostgreSQL时间区间外的数据

核心逻辑

因为存储的是TIME类型(仅时分秒),需分两种场景处理时间区间:

  1. 常规区间(start_time ≤ end_time):比如07:00:12到22:00:00,当前时间不在该区间的条件是:当前时间 < start_time 或者 当前时间 > end_time
  2. 跨天区间(start_time > end_time):比如22:00:00到次日07:00:00,当前时间不在该区间的条件是:当前时间 ≥ start_time 或者 当前时间 ≤ end_time

SQLAlchemy实现示例

假设你的模型为SomeModel,包含start_time和end_time两个TIME类型字段:

1. 使用数据库端的当前时间

from sqlalchemy import func
from sqlalchemy.orm import Session
from your_module import SomeModel  # 替换为你的模型类

# 构建筛选条件
filter_condition = (
    # 常规区间:当前时间不在[start, end]内
    ((SomeModel.start_time <= SomeModel.end_time) & 
     ((func.current_time() < SomeModel.start_time) | (func.current_time() > SomeModel.end_time)))
    |
    # 跨天区间:当前时间不在(end, start)内(即落在[start, 23:59:59]或[00:00:00, end])
    ((SomeModel.start_time > SomeModel.end_time) & 
     ((func.current_time() >= SomeModel.start_time) | (func.current_time() <= SomeModel.end_time)))
)

# 执行查询
with Session() as session:
    out_of_range_records = session.query(SomeModel).filter(filter_condition).all()

2. 传入Python端的当前时间

如果需要用Python生成的时间值(而非数据库当前时间):

from datetime import time
from sqlalchemy.orm import Session
from your_module import SomeModel

# 示例中的当前时间:10:00:01
current_time = time(10, 0, 1)

filter_condition = (
    ((SomeModel.start_time <= SomeModel.end_time) & 
     ((current_time < SomeModel.start_time) | (current_time > SomeModel.end_time)))
    |
    ((SomeModel.start_time > SomeModel.end_time) & 
     ((current_time >= SomeModel.start_time) | (current_time <= SomeModel.end_time)))
)

with Session() as session:
    out_of_range_records = session.query(SomeModel).filter(filter_condition).all()

示例验证

  • 示例1:当前时间=10:00:01,start_time=16:00:12,end_time=22:00:00
    属于常规区间,当前时间 < start_time,满足筛选条件,返回该数据。
  • 示例2:当前时间=10:00:01,start_time=07:00:12,end_time=22:00:00
    属于常规区间,当前时间在[start_time, end_time]内,不满足条件,无返回结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:35:23