Search code examples
pythonpandaspython-datetime

How to retrieve the date from today excluding weekends with datetime or pandas in Python


I want to create a function that takes in a number and returns the {number} days prior to today, excluding weekends.

For example,

from datetime import date, timedelta

def get_date(days = 5):
    today = date.today()
    return today - timedelta(days)

when today is 2020-06-11, it should output 2020-06-04 (excluding 06-06 and 06-07).


Solution

  • Using only Python's built-in libraries:

    from datetime import date, timedelta
    
    def get_date(days = 5):
        today = date.today()
        if days == 0:
            return today
    
        retval = today
        while days > 0:
            retval -= timedelta(days=1)
            if retval.weekday() not in [5,6]:
                days -= 1
        return retval