今月の1日から末日までのデータを取得したい場合
今日の末日を取得する必要がある。
import datetime
import calendar
# 今日の日付を取得
today = datetime.date.today()
# 今月の初日を計算
first_day_of_month = today.replace(day=1)
# 今月の末日を計算
last_day_of_month = today.replace(day=calendar.monthrange(today.year, today.month)[1])
print(f"今月の初日: {first_day_of_month}")
print(f"今月の末日: {last_day_of_month}")
実行すると
今月の初日: 2025-02-01 今月の末日: 2025-02-28
年月を指定して1日~末日のデータを取得するには
form.py
from django import forms
import datetime
class YearMonthForm(forms.Form):
current_year = datetime.date.today().year
YEARS = [(year, f"{year}年") for year in range(2000, current_year + 1)]
MONTHS = [(month, f"{month}月") for month in range(1, 13)]
year = forms.ChoiceField(choices=YEARS, label="年")
month = forms.ChoiceField(choices=MONTHS, label="月")
YEARS: 2000年から現在の年までの選択肢を生成。
MONTHS: 1月から12月までの選択肢を生成。
テンプレート側
<form method="post">
{% csrf_token %}
<label for="id_year">年:</label>
{{ form.year }}
<label for="id_month">月:</label>
{{ form.month }}
<button type="submit">送信</button>
</form>
view.py
from django.shortcuts import render
from .forms import YearMonthForm
import calendar
from datetime import datetime
from your_app.models import YourModel
def my_view(request):
if request.method == "POST":
form = YearMonthForm(request.POST)
if form.is_valid():
year = form.cleaned_data['year']
month = form.cleaned_data['month']
# 月の初日
start_date = datetime(year, month, 1)
# 月の末日
last_day = calendar.monthrange(year, month)[1]
end_date = datetime(year, month, last_day)
data_within_month = YourModel.objects.filter(
created_at__range=(start_date, end_date)
)
else:
form = YearMonthForm()
return render(request, 'your_template.html', {'data': data_within_month})
エラー出るかもしれません。いや出るでしょう。
あくまでも備忘録です。。
適宜修正ください。。m(__)m



コメント