gpt4 book ai didi

python - 按月和日过滤 django 日期时间字段的问题

转载 作者:IT老高 更新时间:2023-10-28 20:45:14 26 4
gpt4 key购买 nike

谁能向我解释为什么以下过滤器在月和日级别不起作用?按年份过滤似乎有效,但其他两个无效。

>>> clicks.count()
36
>>> date = clicks[0].created
>>> date.month
2
>>> date.year
2014
>>> date.day
1
>>> clicks.filter(created__month=2)
[]
>>> clicks.filter(created__month=02)
[]
>>> clicks.filter(created__month='02')
[]
>>> clicks.filter(created__month='2')
[]
>>> clicks.filter(created__month=date.month)
[]
>>> clicks.filter(created__day=date.day)
[]

快速更新以证明我在创建和处理查询集之前得到了相同的行为:

>>> clicks = PreviewClick.objects.filter(created__month = 2)
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = 02)
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = '02')
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = '2')
>>> clicks.count()
0

这里有更多值得深思的地方:

>>> clicks = PreviewClick.objects.all()
>>> counter = 0
>>> for click in clicks:
... if click.created.month == 2:
... counter += 1
...
>>> counter
35

最佳答案

我看到的行为与您完全相同。

如果您查看 documentation对于 1.6 和月份查询集。他们添加了以下段落:

"When USE_TZ is True, datetime fields are converted to the current time zone before filtering. This requires time zone definitions in the database."

如果您将设置中的以下行更改为 False,那么您应该开始获取您期望的数据。

USE_TZ = False

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

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