Looking to leverage datetime
to get the date of beginning and end of the previous week, sunday to saturday.
So, if it's 8/12/13 today, I want to define a function that prints:
Last Sunday was 8/4/2013 and last Saturday was 8/10/2013
How do I go about writing this?
EDIT: okay, so there seems to be some question about edge cases. For saturdays, I want the same week, for anything else, I'd like the calendar week immediately preceding today
's date.
isoweekday() to get a weekday of a given date in Python The weekday() method we used above returns the day of the week as an integer, where Monday is 0 and Sunday is 6. Use the isoweekday() method to get the day of the week as an integer, where Monday is 1 and Sunday is 7.
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 ).
You just need to take today's date. Then subtract the number of days which already passed this week (this gets you 'last' monday). Finally add one week to this date using a timedelta object and voila you get the next monday's date.
datetime.date.weekday returns 0
for Monday. You need to adjust that.
Try following:
>>> import datetime >>> today = datetime.date.today() >>> today datetime.date(2013, 8, 13) >>> idx = (today.weekday() + 1) % 7 # MON = 0, SUN = 6 -> SUN = 0 .. SAT = 6 >>> idx 2 >>> sun = today - datetime.timedelta(7+idx) >>> sat = today - datetime.timedelta(7+idx-6) >>> 'Last Sunday was {:%m/%d/%Y} and last Saturday was {:%m/%d/%Y}'.format(sun, sat) 'Last Sunday was 08/04/2013 and last Saturday was 08/10/2013'
If you are allowed to use python-dateutil:
>>> import datetime >>> from dateutil import relativedelta >>> today = datetime.datetime.now() >>> start = today - datetime.timedelta((today.weekday() + 1) % 7) >>> sat = start + relativedelta.relativedelta(weekday=relativedelta.SA(-1)) >>> sun = sat + relativedelta.relativedelta(weekday=relativedelta.SU(-1)) >>> 'Last Sunday was {:%m/%d/%Y} and last Saturday was {:%m/%d/%Y}'.format(sun, sat) 'Last Sunday was 08/04/2013 and last Saturday was 08/10/2013'
I found the best answer from here working fine in my case
try this
from datetime import datetime,timedelta import time def last_day(d, day_name): days_of_week = ['sunday','monday','tuesday','wednesday', 'thursday','friday','saturday'] target_day = days_of_week.index(day_name.lower()) delta_day = target_day - d.isoweekday() if delta_day >= 0: delta_day -= 7 # go back 7 days return d + timedelta(days=delta_day)
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