Django/Python - Check a date is in current week
Yep, this question is at 2 years ago. Today with more experiences, I recommend using arrow
with less pain in handling date time.
Checkout: https://github.com/crsmithdev/arrow
Since Django 1.11, we you can use week
Field lookup:
Entry.objects.filter(created_at__week=current_week)
It will give you the week from monday to sunday, according to ISO-8601.
To query for the current week:
from datetime import date
current_week = date.today().isocalendar()[1]
isocalendar()
will return a tuple with 3 items: (ISO year, ISO week number, ISO weekday).
Use __range
. You'll need to actually calculate the beginning and end of the week first:
import datetime
date = datetime.date.today()
start_week = date - datetime.timedelta(date.weekday())
end_week = start_week + datetime.timedelta(7)
entries = Entry.objects.filter(created_at__range=[start_week, end_week])