1

I have sqldb where date is encoded as string. By using of sqlalchemy I need to implement query, where date is used as a filter (date within specific range). I tried to define hybrid method, but it seems, that datetime.strptime cannot be used here ("TypeError: strptime() argument 1 must be str, not InstrumentedAttribute")

Do you have any idea (maybe different approach than hybrid method), how to make it working?

Sample code:

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 Answer 1

1

You can use STR_TO_DATE function in MySQL:

from sqlalchemy import func

@date2.expression
def date2(cls):
    return func.str_to_date(cls.date, "%Y-%m-%d")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.