1

Find out all the Businesshours and BusinessDays from the given list. I followed couple of docs about pandas offsets, but could not figure it out. followed stackoverflow as well, here is similar but no luck.

>>> d = {'hours': ['2020-02-11 13:44:53', '2020-02-12 13:44:53', '2020-02-11 8:44:53', '2020-02-02 13:44:53']}
>>> df = pd.DataFrame(d)
>>> df
                hours
0  2020-02-11 13:44:53
1  2020-02-12 13:44:53
2   2020-02-11 8:44:53

3  2020-02-02 13:44:53
>>> y = df['hours']
>>> from pandas.tseries.offsets import *
>>> y.apply(pd.Timestamp).asfreq(BDay())
1970-01-01   NaT
Freq: B, Name: hours, dtype: datetime64[ns]
>>> y.apply(pd.Timestamp).asfreq(BusinessHour())
Series([], Freq: BH, Name: hours, dtype: datetime64[ns])
Laxmikant
  • 2,046
  • 3
  • 30
  • 44

1 Answers1

2

I suppose, you are looking for something like:

bh = pd.offsets.BusinessHour()   # avoid not necessary imports
y.apply(pd.Timestamp).apply(bh.rollforward)

The result is:

0   2020-02-11 13:44:53
1   2020-02-12 13:44:53
2   2020-02-11 09:00:00
3   2020-02-03 09:00:00
Name: hours, dtype: datetime64[ns]

So:

  • two first hours have not been changed (they are within business hours).
  • third (2020-02-11 8:44:53) has been advanced to 9:00 (start of the business day).
  • fourth (2020-02-02 13:44:53 on Sunday) has been advanced to the next day (Monday) at 9:00.

Or, if you want only to check whether particulat date / hour is within business hours, run:

y.apply(pd.Timestamp).apply(bh.onOffset)

The resutl is:

0     True
1     True
2    False
3    False
Name: hours, dtype: bool

meaning that two last date / hours are outside business hours.

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
  • I think `asfreq` is for set new frequency, so I think OP need set BDay or BusinessHour frequncy (for me not working) – jezrael Apr 28 '20 at 06:53
  • @Valdi_Bo - Perfect :) `onOffset` will do the work for me. Thank you very much. I was testing my code on Python shell, so the imported *. ;) – Laxmikant Apr 29 '20 at 07:54