1
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.
anc1revv
  • 1,563
  • 7
  • 24
  • 42

3 Answers3

9

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.

Community
  • 1
  • 1
Serhii Holinei
  • 5,758
  • 2
  • 32
  • 46
2

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

orokusaki
  • 55,146
  • 59
  • 179
  • 257
Rohan
  • 52,392
  • 12
  • 90
  • 87
  • [import datetime] [from django.utils.timezone import utc] [now = datetime.datetime.utcnow().replace(tzinfo=utc)] it tell me to do this, but how can i make the timezone be PST? – anc1revv Aug 26 '12 at 10:04
  • If you have `pytz` installed, you can get it using `import pytz tz=pytz.timezone('US/PST')` – Rohan Aug 26 '12 at 12:02
1

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

Duilio
  • 876
  • 1
  • 10
  • 15