I have a Python list with hours. e.g. [7,8,9,10,17,23,1,2,3]
The hours are in 24 hour format ranging from 0 to 23 (0 = midnight, 23 = 11pm).
I like to determine the start and end hour of consecutive hour blocks. So my desired end result should look be a list, with dictionaries containing the block start and end hours.
Especially determining the block start with a block that passes midnight (from 23 to 0) makes it difficult.
Desired result:
hour_blocks = (
{
"block_nr": 1,
"block_start": 7,
"block_end": 10
},
{
"block_nr": 2,
"block_start": 17,
"block_end": 17
},
{
"block_nr": 3,
"block_start": 23,
"block_end": 3
}
)
I started with a very rough version, but I got stuck (see below). I also couldnt think of any Python libraries that would make this easier (like the datetime or calendar libraries).
i = 0
busy_blocks = []
hour_list = [7,8,9,10,17,23,1,2,3]
start = False
next_hour_connected = False
for hour in hour_list:
if hour == hour_list[i + 1] -1 and not start:
# Next hour is connected and no start is defined
busy_block_start = hour
start = True
continue
if hour == hour_list[i + 1] - 1:
# Next hour is still connected
#if the subsequent hour is not connected, we define the block end
if (hour != hour_list[i + 2] - 2) or next_hour_connected:
busy_block_end = hour
# Save block
busy_blocks.append({
"busy_block_start": busy_block_start,
"busy_block_end": busy_block_end
})
# Reset block
start = False
next_hour_connected = False
else:
# Remember that next
next_hour_connected = True