tags:

views:

561

answers:

5

How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: datetime.weekday() to do it, but I am getting stuck.

I basically want to find today's date and Mondays date to construct a date range query in django using: created__range=(start_date, end_date).

+14  A: 
>>> import datetime
>>> today = datetime.date.today()
>>> today + datetime.timedelta(days=-today.weekday(), weeks=1)
datetime.date(2009, 10, 26)

Some words of explanation:

Take todays date. Subtract the number of days which already passed this week (this gets you 'last' monday). Add one week.

Edit: The above is for 'next monday', but since you were looking for 'last monday' you could use

today - datetime.timedelta(days=today.weekday())
ChristopheD
A: 

Using timedeltas and datetime module:

import datetime
datetime.date.today()+datetime.timedelta(days=-datetime.date.today().weekday())
elzapp
A: 
d = datetime.datetime.today().weekday()

gives you today's day of the week, counting 0 (monday) to 6 (sunday)

datetime.datetime.today() + datetime.timedelta(days=(7-d)%7)

(7-d)%7 gives you days until Monday, or leaves you where you are if today is Monday

foosion
+6  A: 

The advantage of using the dateutil module is that you don't have to think about math or come up with a method of calculation. dateutil does it all for you:

 #!/usr/bin/env python
from dateutil.relativedelta import MO
from dateutil.rrule import rrule,DAILY
import datetime

now=datetime.datetime.now()
rr=rrule(DAILY,byweekday=MO,dtstart=now-datetime.timedelta(7))
next_monday=rr.after(now,inc=False)
print(next_monday.date())
# 2009-10-26

past_monday=rr.before(now,inc=False)
print(past_monday.date())
# 2009-10-19
unutbu
+4  A: 

ChristopheD's post is close to what you want. I don't have enough rep to make a comment :(

Instead of (which actually gives you the next upcoming monday):

>>> today + datetime.timedelta(days=-today.weekday(), weeks=1)
datetime.date(2009, 10, 26)

I would say:

>>> last_monday = today - datetime.timedelta(days=today.weekday())

If you want the previous week, add the 'weeks=1' parameter.

This makes the code more readable since you are subtracting a timedelta. This clears up any confusion caused by adding a timedelta that has negative and positive offsets.

Steven Graham
+1 for your future comment privs!
vgm64
Whooohooo, I can comment now! Thanks.
Steven Graham