3

Given,

column_a = Column(Datetime,...)
column_b = Column(Integer)

dialect - postgresql

How can I make a query like this?

SELECT * from table WHERE column_a + interval '{column_b value} minute' > now()
0

1 Answer 1

0

I had similar problem and didn't found way to convert integer to postgresql interval. I resolved this problem by changing column type from Integer to INTERVAL like this:

from datetime import datetime, timedelta
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, DateTime, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.dialects.postgresql import INTERVAL
from config import DB_CONFIG

Base = declarative_base()


class Model(Base):

    __tablename__ = 'model'
    id = Column(Integer, primary_key=True)
    column_a = Column(DateTime)
    column_b = Column(INTERVAL)


engine = create_engine(
    'postgresql+psycopg2://%s:%s@%s:%d/%s'
    % (DB_CONFIG["user"], DB_CONFIG["password"], DB_CONFIG["host"], 
       DB_CONFIG["port"], DB_CONFIG["db_name"]),
    echo=True
)
Session = sessionmaker(bind=engine)
session = Session()

Base.metadata.create_all(engine)

# INTERVAL type can be set via instance of timedelta
session.add(Model(column_a=datetime.now(), column_b=timedelta(minutes=10)))
session.add(Model(
    column_a=datetime.now() - timedelta(minutes=20),
    column_b=timedelta(minutes=10)
))
session.commit()

result = session.query(Model).filter(
    Model.column_a + Model.column_b > datetime.now()
).all()

for row in result:
    print row.id

Output after first run will be: 1

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.