Eg1. Suppose I have a day 4/30/07 .Then I need to get 4/27/07.
Eg2. Suppose I have a day 6/29/07 .Then I need to get 6/22/07.
Get the last day of the current month and start checking in a loop (which wouldn't cost anything since max loops before finding last friday is 7) for friday. if last day is not friday decrement and the check the day before.
in datetime module you can do something like this: a = date. today() - timedelta(days=1) and then a. weekday() . Where monday is 0 and sunday is 6.
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 can find the next Monday's date easily with Python's datetime library and the timedelta object. You just need to take today's date. Then subtract the number of days which already passed this week (this gets you 'last' monday).
An another and easier way is to use python-dateutil. To get the previous Friday :
>>> from dateutil.relativedelta import relativedelta, FR
>>> from datetime import datetime
>>> datetime(2015, 7, 8) + relativedelta(weekday=FR(-1))
datetime.datetime(2015, 7, 3, 0, 0)
And the next Friday :
>>> datetime(2015, 7, 8) + relativedelta(weekday=FR(+1))
datetime.datetime(2015, 7, 10, 0, 0)
Assuming day
is a datetime.date
or datetime.datetime
object, this code creates a datetime
/date
object for last week's friday:
friday = day - timedelta(days=day.weekday()) + timedelta(days=4, weeks=-1)
Explanation: timedelta(days=day.weekday())
is the offset between monday and day
so adding 4 days and subtracting one week will get you last week's friday.
Of course you can simplify this (+4d -1w = -3d
):
friday = day - timedelta(days=day.weekday() + 3)
Note: To get timedelta
, use from datetime import timedelta
or just import datetime
and use datetime.timedelta
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