Danny O
Danny O

Reputation: 17

Exclude timeslot from pandas daterange

For my application I want to generate some timeslots. While generating these timeslots there needs to be a excluded timeslot.

So let's say I want to generate 30 minute timeslots from 09:00 to 15:00, it will be generated like:

09:00, 09:30, 10:00, 10:30, 11:00, 11:30 .. etc.

But let's say I want to exclude 12:00 to 13:00 because of a break or whatever. How would I achieve this?

Currently I'm generating two timeranges and extending both into an array.

code for this solution:

# method to merge two range strings

first_string = self.create_range_string(start_time, break_start)
second_string = self.create_range_string(break_end, end_time)
        
array_to_extend.extend(first_string)
array_to_extend.extend(second_string)
def create_range_string(self, start, end):
    return pandas.date_range(start=start, end=end, freq=30).strftime('%H:%M')

Is there even a possibility to do something like .exclude(12:00-13:00) ?

Upvotes: 0

Views: 49

Answers (1)

Paulina Khew
Paulina Khew

Reputation: 407

What you could do is use the create_range_string function to loop from 9:00 to 15:00 and then use a python list iteration to remove the numbers between 12 and 13.

import pandas
def create_range_string(start, end, break_start, break_end):
    dates = list(pandas.date_range(start=start, end=end, freq="0.5H").strftime('%H:%M'))
    return [x for x in dates if int(x.split(":")[0]) < break_start or int(x.split(":")[0]) >= break_end]
create_range_string("9:00", "15:00", 12, 13)

The result of this is

['09:00',
 '09:30',
 '10:00',
 '10:30',
 '11:00',
 '11:30',
 '13:00',
 '13:30',
 '14:00',
 '14:30',
 '15:00']

Upvotes: 1

Related Questions