Django模型中的日期过滤器会导致意外行为

时间:2021-02-16 20:27:34

It seems to be easy but it creates confusion for me. My code is

它似乎很容易,但它给我带来了困惑。我的代码是

today = datetime.datetime.now()
StatusObj = Status.objects.filter(taskPeople__people__email = useremail,dateCreated__year = today.year, dateCreated__month = today.month, dateCreated__day = today.day) 

it is expected that it will filter the query whose date is today. But it doesn't filter instead it filter one day back query. when I do.

预计它将过滤日期为今天的查询。但它不会过滤而是过滤一天后的查询。当我做。

today.day
>> 20
Status.objects.filter(taskPeople__people__email = useremail,dateCreated__year = today.year, dateCreated__month = today.month, dateCreated__day = today.day)[0].dateCreated.day
>>19

1 个解决方案

#1


1  

You should use django.utils.timezone.now instead of datetime.datetime.now.

您应该使用django.utils.timezone.now而不是datetime.datetime.now。

from django.utils import timezone
today = timezone.now()
...

Read the question #3 in the troubleshooting section of the timezones docs.

阅读timezones文档的故障排除部分中的问题#3。

#1


1  

You should use django.utils.timezone.now instead of datetime.datetime.now.

您应该使用django.utils.timezone.now而不是datetime.datetime.now。

from django.utils import timezone
today = timezone.now()
...

Read the question #3 in the troubleshooting section of the timezones docs.

阅读timezones文档的故障排除部分中的问题#3。