-3

Is there a way to use Python to get last Friday's date and store it in a variable, regardless of which day of the week the program runs?

That is, if I run the program on Monday June 19th 2021 or Thursday June 22nd 2021, it always returns the previus Friday as a date variable: 2021-07-16.

countunique
  • 4,068
  • 6
  • 26
  • 35
JCarNav
  • 21
  • 1
  • 5

2 Answers2

0

To get the day of the week as an int we use datetime.datetime.today().weekday() and to subtract days from a datetime we use datetime.today() - timedelta(days=days_to_subtract) now we can make a dictionary linking the day of the week to the number of days to subtract and use that dictionary to make a subtraction:

from datetime import datetime, timedelta
d = {0:3,1:4,2:5,3:6,4:0,5:1,6:2}
lastfriday = datetime.today()-timedelta(days=d[datetime.today().weekday()])
kpie
  • 9,588
  • 5
  • 28
  • 50
0

Your question is similar to this one Here's a starting point:

import datetime

def get_last_friday():
    current_time = datetime.datetime.now()
    last_friday = (current_time.date()
        - datetime.timedelta(days=current_time.weekday())
        + datetime.timedelta(days=4, weeks=-1))
    return last_friday
Ahsayn
  • 1
  • 1