python - Sqlalchemy searching dates -


i'm trying search between 2 dates sqlalchemy. if used static dates way.

def secondexercise():  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 

manipulating dates in python quite easy.

today = date.today().strftime("%y/%m/%d") sixthmonth = date(date.today().year, date.today().month-6,date.today().day).strftime("%y/%m/%d") 

the problem is, don't know how implement parameter. this?

for instance in session.query(puppy.name, puppy.weight, puppy.dateofbirth).\                   filter(puppy.dateofbirth <= today, puppy.dateofbirth >= sixthmonth ).order_by(desc("dateofbirth")): 

sqlalchemy supports comparison datetime.date() , datetime.datetime() objects. http://docs.sqlalchemy.org/en/rel_1_0/core/type_basics.html?highlight=datetime#sqlalchemy.types.datetime

you can expose these parameters (replace your_query stuff want constant , not parametrized):

six_months_ago = datetime.datetime.today() - datetime.timedelta(180) today = datetime.datetime.today()  def query_puppies(birth_date=six_months_ago):     puppy in your_query.filter(puppy.dateofbirth.between(birthdate, today)):        print puppy.name # example.. 

also note usage of between clause awesomeness :) 2 seperate clasuses using <= , >= work.

cheers


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -