Pang
Pang

Reputation: 532

Django model filter compare month fail

Suppose I have this model:

class User(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=10)
    last_login = models.DateTimeField(null=True)

Here is one of the records in database,

id=15,
username='yhbohh'
last_login='2015-03-31 10:57:18'

I would like to get a number count of objects with last login of month=3.

I tried in shell,

User.objects.filter(last_login__year=2015).count() # return 80
User.objects.filter(last_login__month=3).count() # return 0
User.objects.filter(last_login__day=31).count() # return 0

May I know why the last 2 queries return no records? I have searched from the other questions and notice than someone may suggest to use date range comparison to solve this problem. But I just wanna know the root cause of this unexpected result.

Thanks a lot!

Upvotes: 1

Views: 125

Answers (1)

awesoon
awesoon

Reputation: 33661

According to Django documentation:

When USE_TZ is True, datetime fields are converted to the current time zone before filtering.

Upvotes: 1

Related Questions