Sqlalchemy comparing datetime.now () date and default date

in the definition of my table, I have a column defined as follows:

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

I want to request an instance when its created date is equal to the current date (for example, if it was created today).

so I tried something like this:

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

it never works because the two dates are compared in seconds, I think, therefore 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 does not work in my situation here. I received an error message: “BinaryExpression Object” or “Comparator” does not have the “days” attribute.

So, how do I make a query that filters instances created on the current day? thanks!

+6
source share
1 answer

I doubt that (datetime.now() - datetime.now()).days works because the datetime.datetime instance has only an attribute named day , not days . Using datetime.now().days will result in an AttributeError: 'datetime.datetime' object has no attribute 'days'

You can try the following:

 from datetime import timedelta res = session.query(Object).filter( (Object.created_date+timedelta(days=1))>datetime.now()) 
+3
source

Source: https://habr.com/ru/post/983329/


All Articles