Get the records between two dates

情到浓时终转凉″ 提交于 2019-12-11 15:43:26

问题


I have a table called Billing which contains the below columns

id| resource_name | start_date | end_date | total_amount

This table is populated with data for different resource with different start_date and end_dates. I need to retrieve the data from the tables.

Sample Record

id| resource_name | start_date          | end_date            | total_amount
1 | abc           | 2018-09-15 03:00:00 | 2018-09-15 04:00:00 | 20

If I write a query like this it will return the above result

select * from billing where start_date >= '2018-09-15 03:00:00' and end_date <= '2018-09-15 04:00:00'

But the below doesn't

select * from billing where start_date >= '2018-09-15 03:00:00' and end_date <= '2018-09-15 03:30:00'

Is there any way to retrieve the same . I am using Django ORM to do the same


回答1:


you can use the django filter method.

Billing.objects.filter(start_date__gte='2018-09-15 03:00:00', end_date__lte='2018-09-15 03:30:00')



回答2:


It's a little confusing from your question, but if you are trying to get all orders that overlap at all with the time period specified, you need to modify the query a bit:

Billing.objects.filter(start_date__lte='2018-09-15 03:30:00', end_date__gt='2018-09-15 03:00:00')

No, that's not written incorrectly. You need to reverse the dates and gte/lte from your original query.

IE: Billing.objects.filter(start_date__lte='the end datetime of your time period', end_date__gt='the start datetime of your time period')

This will ensure that any order that overlaps at all with the 03:00 to 03:30 block is included. All of these will be included:

id| resource_name | start_date          | end_date            | total_amount
1 | abc           | 2018-09-15 03:00:00 | 2018-09-15 04:00:00 | 20
2 | abd           | 2018-09-15 02:00:00 | 2018-09-15 03:00:01 | 20
3 | abe           | 2018-09-01 03:00:00 | 2018-09-20 04:00:00 | 20
4 | abf           | 2018-09-15 03:10:00 | 2018-09-15 03:20:00 | 20

But the following won't:

id| resource_name | start_date          | end_date            | total_amount
5 | abg           | 2018-09-15 02:00:00 | 2018-09-15 03:00:00 | 20
6 | abh           | 2018-09-15 03:30:01 | 2018-09-15 04:00:00 | 20

If you're looking for orders that are exclusively within your time period, use Aman Kumar's answer.




回答3:


Finally I got the pgsql solution. But not sure how to convert the same into Django ORM

SELECT *  FROM billing_lines  WHERE (start_date, end_date) OVERLAPS ('2018-09-15 03:00:00', '2018-09-15 03:30:00');


来源:https://stackoverflow.com/questions/52733598/get-the-records-between-two-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!