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)
.
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.
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.
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.
>>> 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'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With