SQLAlchemy添加datetime列,其中整数列转换为分钟间隔

时间:2014-07-12 21:56:22

标签: python postgresql sqlalchemy flask-sqlalchemy

鉴于,

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

dialect - postgresql

如何进行这样的查询?

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

1 个答案:

答案 0 :(得分:1)

我有类似的问题,并没有找到将整数转换为postgresql间隔的方法。 我通过将列类型从Integer更改为INTERVAL来解决此问题,如下所示:

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

首次运行后的输出将为:1