如何在日期时间字段中按时间过滤? [英] How do I filter by time in a date time field?
本文介绍了如何在日期时间字段中按时间过滤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在模型输入中是datetime字段。我想查询数据,查找中午(start_time)和下午5:00(end_time)之间的所有条目。
In the model 'entered' is a datetime field. I want to query the data to find all entry's that where made between noon(start_time) and 5:00pm (end_time).
selected = Entry.objects.filter(entered__gte=start_time, entered__lte=end_time)
(正如我所料)我收到以下错误:
(as I expected)I get an error of:
"ValidationError: Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format."
所以我知道我可以使用__year,所以我试过。
So I know I can use __year so I tried.
selected = Entry.objects.filter(entered__time__gte=start_time, entered__time__lte=end_time)
我收到错误:
"FieldError: Join on field 'start' not permitted. Did you misspell 'time' for the lookup type?"
推荐答案
您可以使用数据库的机制过滤python:
You could filter in python instead using the db's mechanisms:
for e in Entry.objects.all():
if i.entered.hour>= 9 and i.entered.hour < 17 :# or break down to minutes/seconds
list.append(e)
两个解决方案都是丑陋的,我想。
but both solutions are ugly, i think.
史蒂夫,你必须决定,对你来说不太丑陋:
Steve, you have to decide, what is less ugly for you:
- 处理循环中的大量数据,
- 或使用.extra(..)并绕过orm系统
这篇关于如何在日期时间字段中按时间过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文