varad
varad

Reputation: 8029

django queryset filter with datetime and date

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.

Upvotes: 1

Views: 1586

Answers (3)

catavaran
catavaran

Reputation: 45575

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

Upvotes: 1

miki725
miki725

Reputation: 27861

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

Upvotes: 1

GwynBleidD
GwynBleidD

Reputation: 20539

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.

Upvotes: 1

Related Questions