How to compare dates in sqlalchemy?

戏子无情 提交于 2021-01-27 11:56:04

问题


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?


回答1:


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()



回答2:


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.



来源:https://stackoverflow.com/questions/21301934/how-to-compare-dates-in-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!