Django/Python - Check a date is in current week - python

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.

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

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

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

Related

python get same day last year

how to get same day last year in python
I tried datetime.datetime.now() - relativedelta(years=1) but this doesn't produce the result I'm looking.
Can anyone help. Thanks
example:
20/08/2020 (Thursday) last year will be 22/08/2019 (Thursday)
The answer from Pranav Hosangadi here is very nice, but please note that not every year has 52 weeks! It may be also 53, if you follow the
ISO8601 week numbering standard.
Number of ISO weeks in a year may be get according to this Stack Overflow thread, resulting in you code:
print(datetime.datetime.now())
2020-08-20 22:57:28.061648
def lastweeknumberoflastyear():
return datetime.date(datetime.datetime.now().year-1, 12, 28).isocalendar()[1]
print(datetime.datetime.now() - datetime.timedelta(weeks=lastweeknumberoflastyear()))
2019-08-22 22:57:28.061785
You want the same day of week one year ago. A year has 52 weeks
print(datetime.datetime.now())
2020-08-20 17:56:56.397626
print(datetime.datetime.now() - datetime.timedelta(weeks=52))
2019-08-22 17:56:56.397626
You can do something like:
now = datetime.datetime.now()
last_year = now.replace(now.year - 1)
Note that this will not account for leap years. If you want to find a date exactly 365 days prior, you would instead do something like:
now = datetime.datetime.now()
last_year = now - datetime.timedelta(days=365)
I'd probably do it like this, as a year is not always 365 days.
from datetime import datetime
x = datetime.now()
last_year = datetime(x.year-1,x.month,x.day,x.hour,x.minute,x.second,x.microsecond)
Let's say you want to look at today's date and then get the same date but last year:
today = datetime.date.today()
previous_year = today.year -1
today_last_year = today.replace(year = previous_year)

Python: Find date beginning two months prior to today AND start on a Monday

so I am a beginner with python and have been working with the datetime, time, and timedelta libraries a little bit. I am trying to create a piece of code that gives me the date approximately two months ago(exact_two_months_date) from today (whatever today happens to be). The catch is, I want to find that date approx. two months ago AND begin the actual start_date on the Monday of that week. So in theory, the actual start date will not be exactly two months ago. It will be the week beginning on Monday two months ago from today.
Example pseudocode:
today = '20150425' ## '%Y%m%d' ... Saturday
exact_two_months_date = '20150225' ## EXACTLY two months ago ... Wednesday
start_date = '20150223' ## this is the Monday of that week two months ago
So how do I find the 'start_date' above? If the day exactly two months ago begins on a Saturday or Sunday, then I would just want to go to the next Monday. Hope this is clear and makes sense... Once I find the start date, I would like to increment day by day(only week days) up to 'today'.
Appreciate any feedback, thanks.
Calculating with dates using python-dateutil
If a dependency on a third-party package is an option, then ☞ python-dateutil provides a convenient method to calculate with dates.
Browse the docs for ☞ relativedelta to see the wealth of supported parameters. The more calculations a package needs to do with dates, the more a helper module like dateutil justifies its dependency. For more inspiration on what it has to offer see the ☞ examples page.
Quick run-through:
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> today = datetime.date.today()
>>> two_m_ago = today - relativedelta(months=2)
>>> # print two_m_ago ~> datetime.date(2015, 2, 25)
>>> monday = two_m_ago - datetime.timedelta(days=two_m_ago.weekday())
>>> # print monday ~> datetime.date(2015, 2, 23)
Getting the Monday with weekday()
Once we have the date from two months ago in the variable two_m_ago, we subtract the index of the weekday() from it. This index is 0 for Monday and goes all the way to 6 for Sunday. If two_m_ago already is a Monday, then subtracting by 0 will not cause any changes.
Does something like this work for you?
import datetime
today = datetime.date.today()
delta = datetime.timedelta(days=60) # ~ 2 months
thatDay = today - delta
# subtract weekdays to get monday
thatMonday = thatDay - datetime.timedelta(days=thatDay.weekday())
Honestly, I find working with datetimes to be the hardest thing I ever have to regularly do and I make a lot of mistakes, so I'm going to work through this one and show some of the failures I regularly have with it. Here goes.
Two constraints: 1) Date two months ago, 2) Monday of that week
Date Two Months Ago
Okay, so Python's datetime library has a useful method called replace, which seems like it might help here:
>>> import datetime
>>> now = datetime.date.today()
>>> today
datetime.date(2015, 4, 25)
>>> today.month
4
>>> two_months_ago = today.replace(month=today.month-2)
>>> two_months_ago
datetime.date(2015, 2, 25)
>>> two_months_ago.month
2
But wait: what about negative numbers? That won't work:
>>> older = datetime.date(2015, 01, 01)
>>> older.replace(month=older.month-2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: month must be in 1..12
So there are two solutions:
1) I can build a 1-12 range that cycles forwards or back, or
2) To find two months previous, I can merely replace the day part of my date with the 1st day of the month I'm in and then go back 1 day to the previous month and then replace that day in the previous month with the day I want.
(If you think about it, you'll find that either of these may present bugs if I land on day 31 in a month with fewer days than that, for instance. This is part of what makes datetimes difficult.)
def previous_month(date):
current_day = date.day
first_day = date.replace(day=1)
last_day_prev_month = first_day - datetime.timedelta(days=1)
prev_month_day = last_day_prev_month.replace(day=current_day)
return prev_month_day
>>> today = datetime.date.today()
>>> older = previous_month(today)
>>> older
datetime.date(2015, 3, 25)
Well, let's say we're getting close, though, and we need to include some error-checking to make sure the day we want is a valid date inside the month we land in. Ultimately, the problem is that "two months ago" means a lot more than we think it means when we say it out loud.
Next, we'll take a crack at problem number two: How to get to the Monday of that week?
Well, datetime objects have a weekday method, so this part shouldn't be too hard and here's a nice SO answer on how to do that.
Simple version is: use the difference in weekday integers to figure out how many days to go back and do that using datetime.timedelta(days=days_difference).
Takeaway: Working with datetimes can be tough.
Date manipulation in Python is horribly convoluted. You will save a lot of time by using the arrow package which greatly simplifies these operations.
First install it
pip install arrow
Now your question:
import arrow
# get local current time
now = arrow.now('local')
# move 2 months back
old = now.replace(months=-2)
# what day of the week was that?
dow = old.isoweekday()
# reset old to Monday, for instance at 9:32 in the morning (this is just an example, just to show case)
old = old.replace(days=-dow, hour=9, minute=32, second=0)
print('now is {now}, we went back to {old}'.format(now=now.isoformat(), old=old.isoformat()))
The output:
now is 2015-04-25T20:37:38.174000+02:00, we went back to 2015-02-22T09:32:00.174000+01:00
Note that the various formats, timezones etc. are now transparent and you just need to rely on one package.

Howto calculate first date of week and last date for week in python

I need Calculate dates for week in python
I need this
year = 2012
week = 23
(a,b) = func (year,week)
print a
print b
>>>2012-04-06
>>>2012-06-10
Could you help me ?
The date object contains a weekday() method.
This returns 0 for monday 6 for sunday.
(From googling) here is one solution: http://www.protocolostomy.com/2010/07/06/python-date-manipulation/ )
I think this can be made a little less verbose so here's my stab at it:
def week_magic(day):
day_of_week = day.weekday()
to_beginning_of_week = datetime.timedelta(days=day_of_week)
beginning_of_week = day - to_beginning_of_week
to_end_of_week = datetime.timedelta(days=6 - day_of_week)
end_of_week = day + to_end_of_week
return (beginning_of_week, end_of_week)
Little outdated answer, but there is a nice module called isoweek that really gets the trick done. To answer the original question you could do something like:
from isoweek import Week
week = Week(2012, 23)
print(week.monday())
print(week.sunday())
Hope this helps anybody.
I think #Anthony Sottile's answer should be this:
def week_magic(day):
day_of_week = day.weekday()
to_beginning_of_week = datetime.timedelta(days=day_of_week)
beginning_of_week = day - to_beginning_of_week
to_end_of_week = datetime.timedelta(days=6 - day_of_week)
end_of_week = day + to_end_of_week
return (beginning_of_week, end_of_week)
It works!
I think the answer he is looking for is in datetime.isocalendar(datetime)
It returns a 3-tuple containing ISO year, week number, and weekday.
From any particular year (i.e '2015') one can determine the first day of the first week and then from there keep adding days using the timedelta function to find the particular week requested. With this information one can then return the first and last day of that week.

How can I subtract or add 100 years to a datetime field in the database in Django?

How can I subtract or add 100 years to a datetime field in the database in Django?
The date is in database, I just want to directly update the field without retrieving it out to calculate and then insert.
I would use the relativedelta function of the dateutil.relativedelta package, which will give you are more accurate 'n-years ago' calculation:
from dateutil.relativedelta import relativedelta
import datetime
years_ago = datetime.datetime.now() - relativedelta(years=5)
Then simply update the date field as others have shown here.
Use timedelta. Something like this should do the trick:
import datetime
years = 100
days_per_year = 365.24
hundred_years_later = my_object.date + datetime.timedelta(days=(years*days_per_year))
The .update() method on a Django query set allows you update all values without retrieving the object from the database. You can refer to the existing value using an F() object.
Unfortunately Python's timedelta doesn't work with years, so you'll have to work out 100 years expressed in days (it's 36524.25):
MyModel.objects.update(timestamp=F('timestamp')+timedelta(days=36524.25))
Though setting the number of days in a year as 365.25 (from (365+365+365+366)/4) perfectly offsets the difference-in-days error, it would sometimes lead to unwanted results as you might cause undesirable changes in attributes other than year, especially when you are adding/subtracting 1 or a few years.
If you want to just change the year while preventing changes in other datetime's attributes, just do the algebra on the year attribute like the following:
from datetime import datetime
d = my_obj.my_datetime_field
""" subtract 100 years. """
my_obj.my_datetime_field = datetime(d.year-100, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, d.tzinfo)
my_obj.save()
Hope it helps!
Subtract year from today and use this format.
x = datetime.datetime(2020 - 100, 5, 17)
import datetime
datetime.date(datetime.date.today().year - 100, datetime.date.today().month, datetime.date.today().day)
I Know it's an old question, but I had the problem to find out a good one to solve my problem, I have created this: Use plus(+) or minus(-) to handle with:
import datetime # Don't forget to import it
def subadd_date(date,years):
''' Subtract or add Years to a specific date by pre add + or - '''
if isinstance(date,datetime.datetime) and isinstance(years,int):
day,month,year = date.day , date.month , date.year
#If you want to have HOUR, MINUTE, SECOND
#With TIME:
# day,month,year,hour,minute,second = date.day, date.month,date.year,date.hour,date.minute,date.second
py = year + years # The Past / Futur Year
new_date_str = "%s-%s-%s" % (day,month,py) # New Complete Date
# With TIME : new_date_str = "%s-%s-%s %s:%s:%s" % (month,day,py,hour,minute,second)
try:
new_date = datetime.datetime.strptime(new_date_str,"%d-%m-%Y")
except ValueError: # day is out of range for month (February 29th)
new_date_str = "%s-%s-%s" % (1,month+1,py) # New Complete Date : March 1st
new_date = datetime.datetime.strptime(new_date_str,"%d-%m-%Y")
return new_date
# With TIME : return datetime.datetime.strptime(new_date_str,"%d-%m-%Y %H:%M:%Y")
return None

Datetime problem at start of month in Python

I have a function that removes a file after a certain amount of time. The problem is that it works at later parts of the month, but when I try and remove 7 days from the start of the month it will not substract into the previous month. Does anyone know how to get this to work? The code is below that works out the date and removes the days.
today = datetime.date.today() # Today's date Binary
todaystr = datetime.date.today().isoformat() # Todays date as a string
minus_seven = today.replace(day=today.day-7).isoformat() # Removes 7 days
Thanks for any help.
minus_seven = today - datetime.timedelta(days = 7)
The reason this breaks is that today is a datetime.date; and as the docs say, that means that today.day is:
Between 1 and the number of days in the given month of the given year.
You can see why this works later in the month; but for the first few days of the month you end up with a negative value.
The docs immediately go on to document the correct way to do what you're trying to do:
date2 = date1 - timedelta Computes date2 such that date2 + timedelta == date1.

Categories

Resources