anc1revv
anc1revv

Reputation: 1613

How to filter objects that were created today (Django)

orders = Order.objects.filter(date__range=[datetime.datetime.now(), datetime.timedelta(days=1)])

I guess this doesn't do exactly what i want, but when i type this into my python shell i keep getting this warning.

RuntimeWarning: DateTimeField received a naive datetime (2012-08-26 02:03:25.614372) while time zone support is active.

Upvotes: 1

Views: 11638

Answers (3)

Duilio
Duilio

Reputation: 1036

If you are working with timezone aware dates, I recommend getting the first instant of the day and filter with that.

dt = timezone.now()
start = dt.replace(hour=0, minute=0, second=0, microsecond=0)
Order.objects.filter(created__gte=start)

Note that if you want orders from another day like for instance yesterday, that's quite easy:

dt = timezone.now() - timedelta(days=1)
start = dt.replace(hour=0, minute=0, second=0, microsecond=0)
end = dt.replace(hour=23, minute=59, second=59, microsecond=999999)
Order.objects.filter(created__range=(start, end))

Source here

Upvotes: 1

Rohan
Rohan

Reputation: 53326

Django's datetime objects now support time zones. datetime.datetime.now() returns naive objects (w/o timezone). To compare them you need to make datetime.datetime.now() timezone-aware.

You can use django.utils.timezone, which has an API for making datetime.datetime instances timezone-aware.

For example:

from django.utils import timezone

timezone.make_aware(datetime_object, tzinfo_object)

Refer to Django Time Zones

Upvotes: 2

Serhii Holinei
Serhii Holinei

Reputation: 5864

This may help you: link. I didn`t check this code, but:

import datetime
yesterday = datetime.date.today() - datetime.timedelta(days=1)
orders = Order.objects.filter(date__gt=yesterday)

It will bring all Orders, which date field contains date over yesterday. Since you have no Orders from future, this may work.

Upvotes: 9

Related Questions