1

I need to find the last weekday (without considering holidays). Is there any more elegant/robust way of implementing this than the one I'm currently using?

from datetime import date
b = date.today() - timedelta(days=1)
while b.weekday()>=5:
    b = b - timedelta(days=1)
Javi Torre
  • 724
  • 8
  • 23

1 Answers1

1

Something like this might work (untested):

from datetime import date, timedelta
b = date.today() - timedelta(days=1)

current_day = b.weekday()  # 0 for Monday, 6 for Sunday

# go back 1 day for Sat, 2 days for Sun, 0 for other days
days_to_go_back = max(current_day - 4, 0)  

b -= timedelta(days=days_to_go_back)
Bas Swinckels
  • 18,095
  • 3
  • 45
  • 62