How to get dates for => recent friday,friday of last week , friday of 2nd last week,friday of 3rd last wk ,friday of nth last wk from a single code?
Asked
Active
Viewed 351 times
-1
-
This has been answered - https://stackoverflow.com/questions/18200530/get-the-last-sunday-and-saturdays-date-in-python – GoPackGo Jul 23 '20 at 18:05
-
Does this answer your question? [How to get last Friday?](https://stackoverflow.com/questions/12686991/how-to-get-last-friday) – FObersteiner Jul 23 '20 at 18:54
-
these where helpful thank you the problem is kind of theoretically solved – akhil kn Jul 24 '20 at 19:22
2 Answers
0
im getting this from another question you could use the dateutil library:
from datetime import datetime
from dateutil.relativedelta import relativedelta, FR
lastfriday = datetime.now() + relativedelta(weekday=FR(-1))
print(lastfriday) # lastfriday is a datetime element, do anything with it
to get 2nd last do -2, for 3rd -3 and so on

Avi Baruch
- 112
- 2
- 8
-
hey Avi i am geting this error --AttributeError: type object 'datetime.datetime' has no attribute 'datetime' – akhil kn Jul 24 '20 at 15:57
-
0
Without dateutil
, you could do it this way:
import datetime
import calendar
now = datetime.datetime.now()
dow = now.weekday()
print('Today is {0}, {1}.'.format(calendar.day_name[dow], now.strftime('%m/%d/%y')))
# Find the nearest Monday.
monday = -dow if dow < 4 else 7-dow
# Use the previous week's Friday if today is a Friday.
friday = 4 - (7 if dow == 4 else 0)
last_friday = (now + datetime.timedelta(days=monday+friday, weeks=-1))
print('The date last Friday was {0}.'.format(last_friday.strftime('%m/%d/%y')))
for weeks_ago in range(2, 5):
last_friday = (now + datetime.timedelta(days=monday+friday, weeks=-weeks_ago))
print('The date {0} Fridays ago was {1}.'.format(weeks_ago, last_friday.strftime('%m/%d/%y')))

Rusty Widebottom
- 985
- 2
- 5
- 14
-
when i gave now = ## tomorow date, saturday then it prints The previous Friday is -8 days ago. it should be The previous Friday is -1 days ago. – akhil kn Jul 24 '20 at 16:00
-