Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate DATEDIFF in POSTGRES using SQLAlchemy

I need to calculate DATEDIFF in minutes between 2 columns of timestamp type. There are so many simple examples on the web, but none of them work really much properly using psycopg2 + sqlalchemy. I've tried:

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(),
    )
)

it throws:

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)}]

if I try:

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

I receive:

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)}]

Any ideas how to make it right?

like image 217
Alex-Bogdanov Avatar asked Feb 27 '17 12:02

Alex-Bogdanov


People also ask

How do I calculate days between two dates in PostgreSQL?

To count the difference between dates as days in PostgreSQL or Oracle, you simply need to subtract one date from the other, e.g. arrival - departure . But in most cases, what you really want is the number of days from the first date to the second date inclusively.

Does datediff work in PostgreSQL?

PostgreSQL provides a datediff function to users. The datediff means we can return the difference between two dates based on their specified interval. The datediff function plays an important role in the database management system because datediff functions as a calendar and it is very helpful to users.

Can SQLAlchemy be used with PostgreSQL?

This SQLAlchemy engine is a global object which can be created and configured once and use the same engine object multiple times for different operations. The first step in establishing a connection with the PostgreSQL database is creating an engine object using the create_engine() function of SQLAlchemy.


1 Answers

PostgreSQL does not have a datediff function. To get the number of minutes, use the SQL expression:

trunc((extract(epoch FROM newer_date) - extract(epoch FROM older_date)) / 60)
  • extract(epoch FROM …) converts the timestamp to number of seconds.
  • / 60 converts to seconds to minutes
  • trunc(…) removes the fractional part.

So probably try

sa.func.trunc((
    sa.extract('epoch', datetime.utcnow()) -
    sa.extract('epoch', datetime.utcnow())
) / 60)
like image 187
kennytm Avatar answered Oct 28 '22 22:10

kennytm