使用SQLAlchemy计算POSTGRES中的DATEDIFF

时间:2017-02-27 12:34:29

标签: python postgresql sqlalchemy psycopg2

我需要在两列时间戳类型之间的分钟内计算 DATEDIFF 。 网上有很多简单的例子,但是没有一个使用psycopg2 + sqlalchemy可以正常工作。 我试过了:

from sqlalchemy import as sa
from datetime import datetime

# con is a standard pool of connections :class:Connection
con.execute(
    sa.func.datediff(
        sa.literal_column('minute'),
        datetime.utcnow(),
        datetime.utcnow(),
    )
)
它扔了:

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column "minute" does not exist
LINE 1: SELECT datediff(minute, '2017-02-27T15:04:33.217559'::timest...
                    ^
[SQL: 'SELECT datediff(minute, %(datediff_2)s, %(datediff_3)s) AS datediff_1'] [parameters: {'datediff_3': datetime.datetime(2017, 2, 27, 15, 4, 33, 217596), 'datediff_2': datetime.datetime(2017, 2, 27, 15, 4, 33, 217559)}]

如果我尝试:

con.execute(
    sa.func.datediff(
        'minute',
        datetime.utcnow(),
        datetime.utcnow(),
    )
)

我收到:

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) function datediff(unknown, timestamp without time zone, timestamp without time zone) does not exist
LINE 1: SELECT datediff('minute', '2017-02-27T12:27:49.369724'::time...
           ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
[SQL: 'SELECT datediff(%(datediff_2)s, %(datediff_3)s, %(datediff_4)s) AS datediff_1'] [parameters: {'datediff_4': datetime.datetime(2017, 2, 27, 12, 27, 49, 369740), 'datediff_2': 'minute', 'datediff_3': datetime.datetime(2017, 2, 27, 12, 27, 49, 369724)}]

任何想法如何使它正确?

1 个答案:

答案 0 :(得分:5)

PostgreSQL does not have a datediff function。要获得分钟数,use the SQL expression

trunc((extract(epoch FROM newer_date) - extract(epoch FROM older_date)) / 60)

所以可能试试

sa.func.trunc((
    sa.extract('epoch', datetime.utcnow()) -
    sa.extract('epoch', datetime.utcnow())
) / 60)