Django ORM查詢指定日期範圍內的資料
阿新 • • 發佈:2019-02-20
Django ORM查詢指定日期範圍內的方法
dt_s= datetime.now().date() # 2018-7-15
dt_e = (dt_s- timedelta(7)) # 2018-7-08
objs = Record.objects.filter(end_time__range=[dt_s, dt_e])
objs = Record.objects.filter(Q(end_time__=dt_s) & Q(end_time__lt=dt_e)) # 效果相同
end_time為datetime型別資料
id | end_time | value |
---|---|---|
1 | 2018-07-09 04:23:16 | 1 |
2 | 2018-07-015 04:23:16 | 3 |
使用上面的命令返回的結果為第一條,以下是ORM封裝的SQL語句,因為2018-07-15 04:23:16 比 2018-07-15大
select * from record where end_time between 2018-07-08 and 2018-07-15;
You can use range anywhere you can use BETWEEN in SQL — for dates, numbers and even characters.
Warning
Filtering a DateTimeField with dates won’t include items on the last day, because the bounds are interpreted as “0am on >the given date”. If pub_date was a DateTimeField, the above expression would be turned into this SQL:
SELECT … WHERE pub_date BETWEEN ‘2005-01-01 00:00:00’ and ‘2005-03-31 00:00:00’;
Generally speaking, you can’t mix dates and datetimes.
要將end_time轉換為日期,就能返回兩條資料了
select * from record where date(end_time) between 2018-07-08 and 2018-07-15;