Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django/Python - Check a date is in current week

I would like to do something like this:

entries = Entry.objects.filter(created_at__in = current_week())

How to make it for good performance. Thanks!

Edit: I still have no idea for current_week() function.

like image 783
anhtran Avatar asked Feb 06 '12 11:02

anhtran


People also ask

How do I get the current weekly date in python?

How do YOu get the first and last day of the current week in Python? from datetime import date, timedelta. last_day_of_prev_month = date. today().

How does Django store current date and time?

today() method to get the current local date. By the way, date. today() returns a date object, which is assigned to the today variable in the above program. Now, you can use the strftime() method to create a string representing date in different formats.

How do I get the last week start and end date in python?

You can use datetime. timedelta for that. It has an optional weeks argument, which you can set to -1 so it will subtract seven days from the date . You will also have to subract the current date's weekday (and another one, to even the day since the Monday is 0 ).


2 Answers

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])
like image 58
Daniel Roseman Avatar answered Oct 19 '22 06:10

Daniel Roseman


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).

like image 38
Harper Avatar answered Oct 19 '22 06:10

Harper