All posts from same day django

39 views
Skip to first unread message

Nkansah Rexford

unread,
Jul 22, 2015, 2:54:37 PM7/22/15
to Django users
I currently have:

    @classmethod
   
def get_past_week(self):
        start_date
= datetime.now().date()
        end_date
= datetime.now().date() - timedelta(weeks=1)
       
return MyModel.objects.filter(pub_date__range=(end_date, start_date)).aggregate(Sum('off_hours'))


which simply pulls all posts from the current date minus 7 days

I want to pull posts from within the same day factoring in the time at the moment. Thus if the time is 15:00 GMT now, I want all posts from 14:59:49 GMT back to 00:00:01 GMT of the same day.

How can I do something like that?

Carl Meyer

unread,
Jul 22, 2015, 3:31:19 PM7/22/15
to django...@googlegroups.com
Hi,

On 07/22/2015 12:54 PM, Nkansah Rexford wrote:
> I currently have:
>
> |
> @classmethod
> defget_past_week(self):
> start_date =datetime.now().date()
> end_date =datetime.now().date()-timedelta(weeks=1)
>
> returnMyModel.objects.filter(pub_date__range=(end_date,start_date)).aggregate(Sum('off_hours'))
> |
>
> which simply pulls all posts from the current date minus 7 days
>
> I want to pull posts from within the same day factoring in the time at
> the moment. Thus if the time is 15:00 GMT now, I want all posts from
> 14:59:49 GMT back to 00:00:01 GMT of the same day.
>
> How can I do something like that?

I'll assume `pub_date` is a `DateTimeField`. If it's a `DateField`, then
this query isn't possible unless you change it to a `DateTimeField`.

You want something like:

from datetime import timedelta
from django.utils import timezone

now = timezone.now()
one_day_ago = now - timedelta(days=1)

return MyModel.objects.filter(pub_date__range=(one_day_ago, now))

Carl

signature.asc

Nkansah Rexford

unread,
Jul 22, 2015, 4:26:36 PM7/22/15
to Django users
Thanks Carl

Also got these approaches too, might help someone too: http://stackoverflow.com/questions/31571607/all-posts-from-same-day-only-django

Carl Meyer

unread,
Jul 22, 2015, 4:31:33 PM7/22/15
to django...@googlegroups.com
I just re-read your original post, and my suggestion was wrong - it gets
you all posts from the last 24 hours. Your accepted answer on SO is
right, except that really you should use `django.timezone.now()` instead
of `datetime.now()`.

Carl

signature.asc

Nkansah Rexford

unread,
Jul 22, 2015, 4:46:16 PM7/22/15
to Django users
Yeah, I figured that timezone thing too. Django runs in console with 'naive datetime' bla bla bla all the time without using the timezone
Reply all
Reply to author
Forward
0 new messages