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
  • 17,620
  • 4
  • 18
  • 35
  • 1
    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