3

How can you get the most recent business day in python?

E.g., if today is a business day, I'd like to get today as a datetime object, but if today is a Sunday, I'd like to get Friday as a datetime object, presuming Friday is the most recent business day.

Thanks,

Jack

1 Answers1

8

You can use:

import pandas as pd

pd.datetime.today() - pd.tseries.offsets.BDay(0)

Update

today = pd.datetime(2018,9,2)

np.where((today - pd.tseries.offsets.BDay(0)) > today,
         (today - pd.tseries.offsets.BDay(1)),
         (today - pd.tseries.offsets.BDay(0)))

[output]
Timestamp('2018-08-31 00:00:00')
Chris Adams
  • 18,389
  • 4
  • 22
  • 39
  • 3
    Seems like overkill to me to import `pandas` just for that but.. – rafaelc Sep 06 '18 at 18:47
  • 1
    Chris if I do `datetime.datetime(2018,9,2) - pd.tseries.offsets.BDay(0)`, I would hope to get 31st August 2018 (most recent business day) but I instead get 3rd September (in the future). Is there anything I can do to correct this? –  Sep 06 '18 at 19:54
  • 1
    Hey @Jack I updated my answer. It's not particularly elegant, but should solve your problem for now. I'll have a play and see if there is a better solution – Chris Adams Sep 06 '18 at 20:06
  • `pandas` is often imported – Alfred Wallace Feb 12 '20 at 16:08
  • 1
    Hi Chris, Does this include holidays for say something like the stock market? – MasayoMusic Jun 21 '20 at 22:18
  • Your updated version could be replaced by `pd.tseries.offsets.BDay(1).rollback(today)` (see [docs](https://pandas.pydata.org/pandas-docs/version/0.25.0/reference/api/pandas.tseries.offsets.BDay.rollback.html)). – Seb May 10 '23 at 10:21