1

I have a queryste:

winner_check = Winner.objects.filter(win_date=date.today())

where win_date is datetime and date.today() gives only date... Is there anyway that I can convert win_date to only date and filter this queryset.

I want to filter all the winners which have same date.

Thanks in advance.

varad
  • 7,309
  • 20
  • 60
  • 112
  • try `YourModel.objects.filter(win_date__year='2008', win_date__month='03', win_date__day='27')` put your values – itzMEonTV Feb 15 '15 at 16:05

3 Answers3

1

You can't. But you can create range from 2 datetimes and filter your queryset by it. Also you can separately filter by win_date__year, win_date__month and win_date__day.

GwynBleidD
  • 20,081
  • 5
  • 46
  • 77
1

You can filter using __year, __month and __day:

today = date.today()
Winner.objects.filter(win_date__year=today.year,
                      win_date__month=today.month,
                      win_date__day=today.day)

docs

miki725
  • 27,207
  • 17
  • 105
  • 121
1

The most efficient way is to use the __range lookup between two datetimes or the combination of __gte/__lt lookups for today/tomorrow dates:

import datetime

today = datetime.date.today()
tomorrow = today + datetime.timedelta(days=1)
winner_check = Winner.objects.filter(win_date__gte=today,
                                     win_date__lt=tomorrow)

This will lead to filtering the win_date from TODAY 0:00:00 to TODAY 23:59:59

catavaran
  • 44,703
  • 8
  • 98
  • 85
  • If the purpose is to collect winners in the past 24 hours then it will fail around DST transitions (or any other change in the utc offset of the local timezone). See [Find if 24 hrs have passed between datetimes - Python](http://stackoverflow.com/a/26313848/4279) – jfs Feb 15 '15 at 20:24