【问题标题】:How do I subtract datetimes in SQLite+SQLalchemy?如何在 SQLite+SQLalchemy 中减去日期时间?
【发布时间】:2013-08-10 09:15:48
【问题描述】:

我正在使用 sqlite+sqlalchemy,我正在做 this,我得到一些看起来像这样的 sql:

SELECT task.id as task_id, task.title AS task_title
FROM task
WHERE (SELECT sum(coalesce(intervals."end", CURRENT_TIMESTAMP) - intervals.start) AS sum_1
FROM intervals
WHERE task.id = intervals.task_id) > :param_1

问题是这不起作用,因为我的查询实际上需要如下所示:

...
WHERE (SELECT sum(julianday(coalesce(intervals."end", CURRENT_TIMESTAMP)) - julianday(intervals.start)) AS sum_1
...

但我无法在 SQLAlchemy 中找到 julianday 函数,或者无法准确找到手动更改查询的方法。

我怎样才能改变行为,以便在 sqlite 中真正获得这些值的差异?

【问题讨论】:

    标签: sqlite datetime sqlalchemy


    【解决方案1】:

    SQLAlchemy 不需要显式定义每个数据库引擎中的每个函数。它知道一些标准的,但你可以使用sqlalchemy.func.foobar(arg1, arg2, ...),它会被翻译成SQL中的函数调用foobar(arg1, arg2, ...)。改变

    @time_spent.expression
    def time_spent(cls):
        return func.coalesce(cls.end, func.current_timestamp()) - cls.start
    

    @time_spent.expression
    def time_spent(cls):
        return func.julianday(func.coalesce(cls.end, func.current_timestamp())) - \
               func.julianday(cls.start)
    

    你应该没事。坚持使用 SQLite,因为 julianday 不可移植。

    【讨论】:

    • 啊!完美 - 实际上,当我将 coalesce 错误输入为 coalesc 时,我已经接触到了这一点 - 但我完全忘记了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多