5

I'm working with pandas and want to create a month-long custom date range where the week starts on Sunday night at 6pm and ends Friday afternoon at 4pm. And each day has 22 hours, so for example Sunday at 6pm to Monday at 4pm, Monday 6pm to Tuesday 4pm, etc.

I tried day_range = pd.date_range(datetime(2016,9,12,18),datetime.now(),freq='H') but that always gives me in 24 hours.

Any suggestions?

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
A1122
  • 1,324
  • 3
  • 15
  • 35

1 Answers1

2

You need Custom Business Hour with date_range:

cbh = pd.offsets.CustomBusinessHour(start='06:00', 
                                    end='16:00', 
                                    weekmask='Mon Tue Wed Thu Fri Sat')
print (cbh)
<CustomBusinessHour: CBH=06:00-16:00>

day_range = pd.date_range(pd.datetime(2016,9,12,18),pd.datetime.now(),freq=cbh)
print (day_range)
DatetimeIndex(['2016-09-13 06:00:00', '2016-09-13 07:00:00',
               '2016-09-13 08:00:00', '2016-09-13 09:00:00',
               '2016-09-13 10:00:00', '2016-09-13 11:00:00',
               '2016-09-13 12:00:00', '2016-09-13 13:00:00',
               '2016-09-13 14:00:00', '2016-09-13 15:00:00',
               ...
               '2016-10-11 08:00:00', '2016-10-11 09:00:00',
               '2016-10-11 10:00:00', '2016-10-11 11:00:00',
               '2016-10-11 12:00:00', '2016-10-11 13:00:00',
               '2016-10-11 14:00:00', '2016-10-11 15:00:00',
               '2016-10-12 06:00:00', '2016-10-12 07:00:00'],
              dtype='datetime64[ns]', length=252, freq='CBH')

Test - it omit Sunday:

day_range = pd.date_range(pd.datetime(2016,9,12,18),pd.datetime.now(),freq=cbh)[45:]
print (day_range)
DatetimeIndex(['2016-09-17 11:00:00', '2016-09-17 12:00:00',
               '2016-09-17 13:00:00', '2016-09-17 14:00:00',
               '2016-09-17 15:00:00', '2016-09-19 06:00:00',
               '2016-09-19 07:00:00', '2016-09-19 08:00:00',
               '2016-09-19 09:00:00', '2016-09-19 10:00:00',
               ...
               '2016-10-11 08:00:00', '2016-10-11 09:00:00',
               '2016-10-11 10:00:00', '2016-10-11 11:00:00',
               '2016-10-11 12:00:00', '2016-10-11 13:00:00',
               '2016-10-11 14:00:00', '2016-10-11 15:00:00',
               '2016-10-12 06:00:00', '2016-10-12 07:00:00'],
              dtype='datetime64[ns]', length=207, freq='CBH')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • What if I want sunday included but in nonuniform pattern? So for example I want Monday to Thursday start = 00:00, end = 16:00, then again start = 18:00 to end = 24:00, Friday start = 00:00, end = 16:00 and Sunday start = 18:00, end = 24:00? Could the function handle this? – A1122 Oct 14 '16 at 06:07
  • Maybe you need create 2 ranges and then substract it. – jezrael Oct 14 '16 at 06:09
  • I try create `starts` time which is higher as end, but it return wrong result. Maybe trere is problem this Custom Business Hours are buggy. – jezrael Oct 14 '16 at 06:10