How do I filter by time in a date time field?

后端 未结 7 1955
野趣味
野趣味 2021-01-18 03:49

In the model \'entered\' is a datetime field. I want to query the data to find all entry\'s that where made between noon(start_time) and 5:00pm (end_time).

s         


        
7条回答
  •  礼貌的吻别
    2021-01-18 04:42

    I don't believe there's built-in support for this, but you can pass extra where-clause parameters (warning: some possibility of introducing DB-dependent behaviour here).

    For example, on Postgres, something like:

    Entry.objects.extra(where=['EXTRACT(hour from entered) >= 12 and '\
                        'EXTRACT(hour from entered) < 17'])
    

    If you're using potentially unsafe input to determine the values 12 and 17, note that you can also specify a params option to extra that will ensure proper quoting and escaping, and then use the standard sql %s placeholders in your where statement.

提交回复
热议问题