Query datetime by today's date in Django

前端 未结 7 486
梦谈多话
梦谈多话 2021-01-31 08:16

I\'m saving datetime in the db for an object. I\'d like to query against the db and select anything from todays date, not datetime.

What\'s the

相关标签:
7条回答
  • 2021-01-31 08:43

    There is a new __date field lookup in Django 1.9 you can use:

    Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
    Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
    

    Queryset API

    0 讨论(0)
  • 2021-01-31 08:45

    You can also do something like this:

    today = date.today()
    invoice_for_today = Invoice.objects.filter(date__year=today.year, date__month=today.month, date__day=today.day)
    
    0 讨论(0)
  • 2021-01-31 08:47

    To get entries from the Last 24 hours you can use:

    from datetime import datetime, timedelta
    
    Entry.objects.filter(pub_date__gte = datetime.now() - timedelta(days=1)) 
    
    0 讨论(0)
  • 2021-01-31 08:49

    in django<1.9

    from django.utils.timezone import datetime #important if using timezones
    today = datetime.today()
    foo_for_today = Foo.objects.filter(datefield__year=today.year, datefield__month=today.month, datefield__day=today.day)
    

    in django>1.9, as they added the date keyword

    foo_for_today = Foo.objects.filter(datefield__date=datetime.date.today())
    
    0 讨论(0)
  • 2021-01-31 08:50

    Try using the keys date__gte and date__lte. You can pass in two datetime objects marking the boundaries of what you want to match.

    0 讨论(0)
  • 2021-01-31 08:53

    I remember there being plans to add a __date field lookup to make this easier, but as it stands the "standard" way of doing it is

    today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
    today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
    Invoice.objects.get(user=user, date__range=(today_min, today_max))
    
    0 讨论(0)
提交回复
热议问题