23

In Python, given a date, how do I find the preceding weekday? (Weekdays are Mon to Fri. I don't care about holidays)

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Lobert
  • 467
  • 1
  • 4
  • 10

4 Answers4

54

Simply subtract a day from the given date, then check if the date is a weekday. If not, subtract another, until you do have a weekday:

from datetime import date, timedelta
def prev_weekday(adate):
    adate -= timedelta(days=1)
    while adate.weekday() > 4: # Mon-Fri are 0-4
        adate -= timedelta(days=1)
    return adate

Demo:

>>> prev_weekday(date.today())
datetime.date(2012, 8, 20)
>>> prev_weekday(date(2012, 8, 20))
datetime.date(2012, 8, 17)

Alternatively, use an offset table; no need to make this a mapping, a tuple will do just fine:

_offsets = (3, 1, 1, 1, 1, 1, 2)
def prev_weekday(adate):
    return adate - timedelta(days=_offsets[adate.weekday()])
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

This is an old question, but anyway, a simpler way to do that, which doesn't require loops

from datetime import datetime, timedelta
today = datetime.today() # Today date
weekday = 6
days = today.isoweekday() - weekday
if days<0:
    days += 7
previous_date = today - timedelta(days=days)
print(previous_date)
1

See the datetime module, in particular the date() and weekday() function. For example:

import datetime

temp = datetime.date(2012,8,21) # Today's date: 2012/08/21
print temp.weekday()

This will output 1. 0 stands for Monday, 1 for Tuesday, etc., until 6 for Sunday. Finding the preceding weekday is easy from here.

HerrKaputt
  • 2,594
  • 18
  • 17
1

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.

Swair
  • 1,503
  • 2
  • 15
  • 27