how to change start end time in CustomBusinessHour

2020-04-19 12:41发布

I want to change start end time in CustomBusinessHour if i get monday in weekmask list from startdate and enddate . start = 00:01 end = 23:59

i am trying to change this start to 07:00 and end =23:59 if i get monday b/w startdate and enddate

data = { 
    'start': ['2018-10-29 18:48:46.697000',
              '2018-10-29 19:01:10.887000',
              '2018-10-22 17:42:24.467000'], 
    'end': ['2018-10-31 17:56:38.830000',
            '2018-11-27 09:31:39.967000',
            '2018-11-28 18:33:35.243000' ]   
}
df = pd.DataFrame(data)

bh = CustomBusinessHour(calendar=USFederalHolidayCalendar(),start='00:01', end='23:59')
df['Hours_diff'] = df.apply(lambda x: len(pd.date_range(start=x.start, end=x.end, freq= bh)),axis=1)

1条回答
家丑人穷心不美
2楼-- · 2020-04-19 13:22

You could use apply with a function, to feed the start and end datetime for each row. Then you use a mask on top of your CustomBusinessHour.

import pandas as pd
from pandas.tseries.offsets import CustomBusinessHour
from pandas.tseries.holiday import USFederalHolidayCalendar

data = { 
    'start': ['2018-10-29 18:48:46.697000',
              '2018-10-29 19:01:10.887000',
              '2018-10-22 17:42:24.467000'], 
    'end': ['2018-10-31 17:56:38.830000',
            '2018-11-27 09:31:39.967000',
            '2018-11-28 18:33:35.243000' ]   
}
df = pd.DataFrame(data)

bh = CustomBusinessHour(calendar=USFederalHolidayCalendar(), start='00:01', end='23:59')

def f(x):
    idx = pd.date_range(start=x.start, end=x.end, freq= bh)
    mask = ~((idx.dayofweek == 0) & (idx.hour <= 7))

    return len(idx[mask])

df['Hours_diff'] = df.apply(f, axis=1)

Gives

                        start                         end  Hours_diff
0  2018-10-29 18:48:46.697000  2018-10-31 17:56:38.830000          42
1  2018-10-29 19:01:10.887000  2018-11-27 09:31:39.967000         391
2  2018-10-22 17:42:24.467000  2018-11-28 18:33:35.243000         527

Make sure that's correct, I haven't checked.

查看更多
登录 后发表回答