gpt4 book ai didi

python - 如何在日期时间字段中按时间过滤?

转载 作者:太空狗 更新时间:2023-10-29 21:41:19 25 4
gpt4 key购买 nike

在模型中,“entered”是一个日期时间字段。我想查询数据以查找在中午(开始时间)和下午 5:00(结束时间)之间进行的所有条目。

selected = Entry.objects.filter(entered__gte=start_time, entered__lte=end_time)

(如我所料)我收到以下错误:

"ValidationError: Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format."

所以我知道我可以使用 __year,所以我尝试了。

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?"

最佳答案

我不相信对此有内置支持,但你可以通过 extra where-clause参数(警告:可能会在此处引入依赖于数据库的行为)。

例如,在 Postgres 上,类似于:

Entry.objects.extra(where=['EXTRACT(hour from entered) >= 12 and '\
'EXTRACT(hour from entered) < 17'])

如果您使用可能不安全的输入来确定值 1217,请注意您还可以为 extra 指定一个参数选项,以确保正确引用和转义,然后在 where 语句中使用标准的 sql %s 占位符。

关于python - 如何在日期时间字段中按时间过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/917996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com