Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Monday's date with Python

Tags:

python

django

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

like image 780
Joe Avatar asked Oct 25 '09 20:10

Joe


People also ask

How do I get the weekly date in Python?

YOu can use the isocalender function from the datetime module to get the current week. Create the object of the date first, then call isocalender() on this object. This returns a 3-tuple of Year, Week number and Day of Week.

What does date () do in Python?

The date class is used to instantiate date objects in Python. When an object of this class is instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class needs three mandatory arguments year, month and date.

How do you get next Friday in Python?

On Friday, this code returns the same day. To get the next, use (3-today. weekday())%7+1 . Just the old x%n to ((x-1)%n)+1 conversion.


2 Answers

>>> 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()) 
like image 99
ChristopheD Avatar answered Sep 28 '22 11:09

ChristopheD


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.

like image 39
Steven Graham Avatar answered Sep 28 '22 10:09

Steven Graham