How to compare dates in sqlalchemy?

I have the following simple setup, where fromDate and toDate are strings on the format "YYYY-MM-DD":

class SomeType(Base):
    date = Column(DateTime)

def findAll(fromDate, toDate):
    return session.query(SomeType).filter(SomeType.date >= fromDate, SomeType.date <= toDate).all()

The problem is that it doesn't find what I want it to find unless I modify the input dates like this:

def findAll(fromDate, toDate):
    fromDate = fromDate + " 00:00"
    toDate = toDate + " 24:00"
    return session.query(SomeType).filter(SomeType.date >= fromDate, SomeType.date <= toDate).all()

But that doesn't look good. Any ideas on how I can do this the right way?

Answers


How about using datetime.datetime objects instead of strings for fromDate, toDate?

from datetime import datetime, timedelta

def findAll(fromDate, toDate):
    fromDate = datetime.strptime(fromDate, '%Y-%m-%d')
    toDate = datetime.strptime(toDate, '%Y-%m-%d') + timedelta(days=1)
    return session.query(SomeType).filter(
        SomeType.date >= fromDate,
        SomeType.date < toDate).all()

The problem is that your SomeType.date column is not simple date, but is datetime column, so it contains also a time component.

This type mismatch is the cause of your problem. If this is the case then following should work:

session.query(SomeType).filter(func.date(SomeType.date) >= fromDate, func.date(SomeType.date) <= toDate).all()

where we basically cast datetime to date using DATE(...) function of MySql.

However, I would probably also prefer working with date(time) data types instead of strings. You are just lucky that most databases implicitly allow parsing of ISO-compliant string representations of DATEs.


Need Your Help

Display simple HTML in a native BlackBerry application

html user-interface blackberry custom-controls browserfield

I want to be able to display some simple chunks of HTML in my native BlackBerry app, NOT returned from a URL. This is similar to existing Stackoverflow questions (e.g. here and here), but I need h...