首页 > 解决方案 > SQLAlchemy:两个日期之间的差异

问题描述

我想知道在 SQLAlchemy 上工作的两个日期之间的区别。使用 Postgresql 我有以下工作:

SELECT
    EXTRACT(EPOCH FROM ('2019-02-11 17:59:05.953894'::timestamp - '2019-02-11 17:59:01.953894'::timestamp))

但是,在 SQLAlchemy 中尝试相同时遇到问题:

session.query(func.extract('epoch',func.date(subquery.c.dt_final.cast(Date)))-
                                   func.date(subquery.c.dt_start.cast(Date))).all()

收到此错误:

ProgrammingError: (psycopg2.errors.UndefinedFunction) operator does not exist: double precision - date
LINE 1: ...h FROM date(CAST(anon_2.dt_final AS DATE))) - date(CAS...
                                                             ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

在 SQLAlchemy 中获取两个日期之间差异的正确方法是什么?

谢谢

标签: pythonpostgresqlsqlalchemy

解决方案


您可能需要从时间戳切换到日期时间,但是有一个名为 timediff() 的内置函数,它的工作原理类似于 count() 和 max()。我不熟悉 SQLalchemy,但它应该很普遍。


推荐阅读