Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the Friday of previous/last week in python

Tags:

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.

like image 259
Jibin Avatar asked May 30 '11 06:05

Jibin


People also ask

How do I get last Friday in Python?

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.

How do I get previous weekday in Python?

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.

How do I get last week's startdate and Enddate in Python?

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

How do I get last week Monday date in Python?

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


2 Answers

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)
like image 39
ychab Avatar answered Dec 28 '22 02:12

ychab


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

like image 70
ThiefMaster Avatar answered Dec 28 '22 03:12

ThiefMaster