我有以下简单的设置,其中fromDate和toDate是格式为“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()
问题是它找不到我想要它找到的东西,除非我像这样修改输入日期:
def findAll(fromDate, toDate):
fromDate = fromDate + " 00:00"
toDate = toDate + " 24:00"
return session.query(SomeType).filter(SomeType.date >= fromDate, SomeType.date <= toDate).all()
但这看起来并不好.关于如何以正确的方式做到这一点的任何想法?
最佳答案 如何使用
datetime.datetime
对象代替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()