3

I have a Django application where I have a view that returns the count of the users who did login today. Corresponding statement is as follows:

login_count= User.objects.filter(last_login__startswith=timezone.now().date()).count()

I want to get the count of users who did login once in the last week and last the month. Like, here timezone.now() returns today's date, is there anything like range which will cover a week or a month?

1

1 Answer 1

4

Yes, there is, and its even named range.

Example

import datetime
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
User.objects.filter(last_login__range=(start_date, end_date))

Of for the last week

today = datetime.date.today()
last_week = today - datetime.timedelta(days=7)
User.objects.filter(last_login__range=(last_week, today))

However,

Filtering a DateTimeField with dates won’t include items on the last day, because the bounds are interpreted as “0am on the given date”. If pub_date was a DateTimeField, the above expression would be turned into this SQL:

A quick solution would be to simply add a day, so the date range includes up to the last minute of today, but not more (also update last_week).

today = datetime.date.today() + datetime.timedelta(days=1)
last_week = datetime.date.today() - datetime.timedelta(days=7)
User.objects.filter(last_login__range=(last_week, today))
Sign up to request clarification or add additional context in comments.

5 Comments

Okay great! But now start_date and end_date are hard coded. It is something which will be called everyday, so start_date could be datetime.date(timezone.now().date()). How can I extend it for end_date?
Is timezone.now().date() - timedelta(days=7) the correct direction?
Yes, correct. Had also just added it to the answer.
However, there is one problem, login_count returns me 2 as 2 users logged in today and the query in answer returns me 0, ideally this also should return 2 as today is still part of the week. can datetime.date.today() be converted to timezone.now().date()?
Added to my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.