![](/img/trans.png)
[英]select records by date, where date is 15th ot the previous business day of the month
[英]Django ORM filter records between last month 15th date to current month 15th date
我想過濾從上個月的第 15 天到當月的第 15 天的查詢集記錄。
有人知道該怎么做嗎?
模型.py
class Book(models.Model):
name = models.CharField(max_length=100, null=True)
author = models.CharField(max_length=100, null=True)
created_on = models.DateTimeField(auto_now_add=True)
視圖.py
class BookView(View):
def get(self, *args, **kwags):
start_date = '15th_of_previous_month'
end_date = '15th_of_current_month'
qs = Book.objects.filter(created_on__gte=start_date,created_on__lt=end_date)
...
您可以通過以下方式獲得當月的 15 日:
from django.utils.timezone import now
this_month_15 = now().date().replace(day=15)
可以通過減去 15 天來計算上個月,然后再次將day
參數替換為15
:
from datetime import timedelta
prev_month_15 = (this_month_15 - timedelta(days=15)).replace(day=15)
這就是我嘗試解決它的方式:
import datetime
today = datetime.date.today()
first = today.replace(day=1) # first date of current month
previous_month_date = first - datetime.timedelta(days=1) # this will be the last day of previous month
start_date = datetime.datetime.strptime(str(previous_month_date.year) + '-' + str(previous_month_date.month) + '-15', '%Y-%m-%d')
end_date = first + datetime.timedelta(days=15)
qs = Book.objects.filter(created_on__gte=start_date,created_on__lt=end_date)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.