0

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).

Yoshi
  • 172
  • 7
landy
  • 3
  • 1
  • 1
    Does this answer your question? [Python - Exclude weekends between two Dates](https://stackoverflow.com/questions/46386764/python-exclude-weekends-between-two-dates) – Yoshi Jun 12 '20 at 01:21

3 Answers3

1

We can do BDay

from pandas.tseries.offsets import BDay

pd.to_datetime('2020-06-11')-BDay(5)

#Timestamp('2020-06-04 00:00:00')
BENY
  • 317,841
  • 20
  • 164
  • 234
0

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
Mike Henderson
  • 2,028
  • 1
  • 13
  • 32
0

https://numpy.org/doc/stable/reference/generated/numpy.busday_offset.html

import numpy as np
from datetime import date

today = date.today()
days = -5
np.busday_offset(today,days)
predmod
  • 399
  • 4
  • 6
  • Your solution works well, but is there a way to convert it into a datetime object? – landy Jun 12 '20 at 02:56
  • of course, sorry, I have not though to provide it ```x = np.busday_offset(today,days); converted=x.astype('O')``` or simply ```str(x)``` or ```x.astype(datetime)``` see https://numpy.org/doc/stable/reference/arrays.datetime.html and SO has many answers about this conversion .. I also usually inspect interactively the advertised methods and attributes of the object by ```dir(x)``` in ipython to see some info if the class is new to me and I am too lazy to search the api documentation. – predmod Jun 12 '20 at 03:36
  • and here is a full blown discussion https://stackoverflow.com/questions/13703720/converting-between-datetime-timestamp-and-datetime64 – predmod Jun 12 '20 at 03:41