按月和日过滤django datetime字段的问题 [英] Problems filtering django datetime field by month and day

查看:212
本文介绍了按月和日过滤django datetime字段的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释为什么以下过滤器在月和日级别不工作?过滤年份似乎有效,但不是其他两个。

 >>> 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)
[]

快速更新演示在创建和处理查询器之前我得到相同的行为:

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

这里有更多的想法:

 >>> click = PreviewClick.objects.all()
>>> counter = 0
>>>>点击次数:
...如果click.created.month == 2:
... counter + = 1
...
>>>柜台
35


解决方案

和你一样的行为。



如果您检查文档,以及月份查询。他们添加了以下段落:


当USE_TZ为True时,datetime字段将在过滤之前转换为当前时区,这需要时间数据库中的区域定义。


如果将设置中的以下行更改为False,则应该开始获取数据你想要的。

  USE_TZ = False 


Can someone explain to me why the following filters are not working at the month and day level? Filtering by year seems to work, but not the other two.

>>> 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)
[]

A quick update to demonstrate that I am getting the same behavior before creating and dealing with a queryset:

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

Here's more food for thought:

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

解决方案

I was seeing exactly the same behaviour as you.

If you check the documentation for 1.6 and the month queryset. They have added the following paragraph:

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

If you change the following line in your settings to False, then you should start getting the data back that you're expecting.

USE_TZ = False

这篇关于按月和日过滤django datetime字段的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆