我试图用sqlalchemy在两个日期之间进行搜索。如果我使用静态日期就会这样。
def secondExercise():
for instance in session.query(Puppy.name, Puppy.weight, Puppy.dateOfBirth).\
filter(Puppy.dateOfBirth <= '2015-08-31', Puppy.dateOfBirth >= '2015-02-25' ).order_by(desc("dateOfBirth")):
print instance
在python中操作日期非常简单。
today = date.today().strftime("%Y/%m/%d")
sixthmonth = date(date.today().year, date.today().month-6,date.today().day).strftime("%Y/%m/%d")
问题是,我不知道如何将其作为参数实现。对此有何帮助?
for instance in session.query(Puppy.name, Puppy.weight, Puppy.dateOfBirth).\
filter(Puppy.dateOfBirth <= today, Puppy.dateOfBirth >= sixthmonth ).order_by(desc("dateOfBirth")):
答案 0 :(得分:0)
SQLAlchemy支持datetime.date()和datetime.datetime()对象的比较。 http://docs.sqlalchemy.org/en/rel_1_0/core/type_basics.html?highlight=datetime#sqlalchemy.types.DateTime
您可以将这些作为参数公开(将your_query替换为您希望保持恒定而不是参数化的所有内容):
six_months_ago = datetime.datetime.today() - datetime.timedelta(180)
today = datetime.datetime.today()
def query_puppies(birth_date=six_months_ago):
for puppy in your_query.filter(Puppy.dateOfBirth.between(birthdate, today)):
print puppy.name # for example..
还要注意使用between子句的一些额外的超棒:) 但使用&lt; =和&gt; =的两个单独的clasuses也可以。
欢呼声