class Journal(Base):
__tablename__ = '_1SJOURN'
rid = Column("ROW_ID", Integer, primary_key=True)
journal_id = Column("IDJOURNAL", Integer)
iddoc = Column("IDDOC", String)
iddocdef = Column("IDDOCDEF", Integer)
datetime = Column("DATE_TIME_IDDOC", String)
表的字段为DATE_TIME_IDDOC,如200809305DU3F4 65P
,前8个字符为日期。我需要选择日期介于s = 20070503,e = 20090503之间的行。
我试过了:
filter(
and_(func.convert(sql.literal_column('DATE'), Journal.datetime, sql.literal_column('1,8')) > s,
func.convert(sql.literal_column('DATE'), Journal.datetime, sql.literal_column('1,8')) < e))
答案 0 :(得分:0)
首先,为什么不能将“datetime”列拆分为两列:datetime和“other_info”?您的表格结构未经过优化。如果它看起来如下所示,那么实现您想要的更容易。更容易和正确。
class Journal(Base):
__tablename__ = '_1SJOURN'
rid = Column("ROW_ID", Integer, primary_key=True)
journal_id = Column("IDJOURNAL", Integer)
iddoc = Column("IDDOC", String)
iddocdef = Column("IDDOCDEF", Integer)
datetime = Column("DATE_TIME", DateTime)
other = Column("OTHER", String)
# here I do not use `and_`, because it used by default
Session.query(Journal).filter(Journal.datetime > s, Journal.datetime < e)
但是,如果你真的想要它,那就是你的查询。原始SQL(对于Postgresql,其他DBMS具有相同的功能,但具有其他名称):
SELECT * FROM journal WHERE to_timestamp(left(DATE_TIME_IDDOC, 8), 'YYYYMMDD') > '2008-10-01' AND to_timestamp(left(DATE_TIME_IDDOC, 8), 'YYYYMMDD') < '2010-01-20';
SQLAlchemy查询:
filter_col = func.to_timestamp(func.left(Journal.datetime, 8), 'YYYYMMDD')
Session.query(Journal).filter(filter_col > s, filter_col < e)
答案 1 :(得分:0)
and_(func.convert(sql.literal_column('datetime'),func.substring(Journal.datetime, 1,8)) > s ,
func.convert(sql.literal_column('datetime'), func.substring(Journal.datetime, 1, 8)) < e)).filter(