Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Previous weekday in Python

Tags:

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

like image 729
Lobert Avatar asked Aug 21 '12 11:08

Lobert


People also ask

How do I get the 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 convert a date to a string in Python?

To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.


1 Answers

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()]) 
like image 50
Martijn Pieters Avatar answered Sep 21 '22 20:09

Martijn Pieters