简体   繁体   中英

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.

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM