SQLAlchey查询日期过滤器,带字符串格式

时间:2020-03-17 21:33:08

标签: mysql flask sqlalchemy

我有sqldb,其中日期编码为字符串。 通过使用sqlalchemy,我需要实现查询,其中日期用作过滤器(特定范围内的日期)。 我试图定义混合方法,但似乎无法在此处使用datetime.strptime(“ TypeError:strptime()参数1必须为str,而不是InstrumentedAttribute”

您有什么想法(也许不同于混合方法),如何使它起作用?

示例代码:

class Sample(db.Model):
__tablename__ = "sample"

id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.String(32))

@hybrid_property
def date2(self):
    return datetime.datetime.strptime(self.date, "%Y-%m-%d")

@date2.expression
def date2(cls):
    return datetime.datetime.strptime(cls.date, "%Y-%m-%d")

...

date_min = datetime.datetime(2020, 1, 1)
date_max = datetime.datetime(2020, 3, 31)
out = Sample.query.filter_by(date2 > date_min, date2 < date_max).all()

1 个答案:

答案 0 :(得分:1)

您可以在MySQL中使用STR_TO_DATE函数:

from sqlalchemy import func

@date2.expression
def date2(cls):
    return func.str_to_date(cls.date, "%Y-%m-%d")