Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy filter by comparing datetime.now() and column default date

in my table definition, i have a column defined like this:

created_date = Column(DateTime, nullable=False, default=datetime.now)

i want to query a instance when its created date is equal to current date(eg, if it is created today).

so i tried something like this:

res = session.query(Object).filter(datetime.now() == Object.created_date)

it never works because two dates are compared in seconds i guess, so they will never be equal to each other. then i tried this:

res = session.query(Object).filter((datetime.now() - Object.created_date).days < 1)

while (datetime.now() - datetime.now()).days works in python, it doesnt work in my situation here. i got error says: Neither 'BinaryExpression' object nor 'Comparator' object has an attribute 'days'.

So how should i do a query that filters instances created on a current day? thanks!

like image 530
shangsunset Avatar asked Mar 04 '15 15:03

shangsunset


1 Answers

I doubt that (datetime.now() - datetime.now()).days works since datetime.datetime instance only have attribute named day rather than days. Using datetime.now().days would result in AttributeError: 'datetime.datetime' object has no attribute 'days'

You might try this:

from datetime import timedelta

res = session.query(Object).filter(
    (Object.created_date+timedelta(days=1))>datetime.now())
like image 102
Paul Lo Avatar answered Oct 12 '22 20:10

Paul Lo