如何比较sqlalchemy中的日期? [英] How to compare dates in sqlalchemy?

查看:63
本文介绍了如何比较sqlalchemy中的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的设置,其中 fromDate 和 toDate 是格式为YYYY-MM-DD"的字符串:

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?

推荐答案

如何使用 datetime.datetime 对象而不是 fromDatetoDate?

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

这篇关于如何比较sqlalchemy中的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆