Sub topic 14
Optional: Find Free Gaps with a Script
This chapter is optional. Everything earlier in the tutorial works with only a calendar application. A script helps when you want to answer a question such as "Which days this week still have a 90-minute gap?" without scanning the grid by eye. It also gives you a way to check a week's schedule against the rules you chose for block length and placement.
Prerequisites
This chapter assumes:
- You can read and run a short Python 3.9+ script. The
datetimeandzoneinfomodules are in the standard library. - You know the block length and placement you chose earlier, such as "at least 90 minutes, preferably before noon".
- You can export or copy your busy times from your calendar. This chapter hard-codes them to keep the logic visible.
The idea: sweep a cursor through the day
A free gap is the space between one busy interval and the next. To find the gaps:
- Sort the busy intervals by start time.
- Put a cursor at the start of your working day.
- For each busy interval, compare its start to the cursor. If the distance is at least your minimum block length, record a gap from the cursor to that start.
- Move the cursor to the later of its current position and the interval's end.
- After the last interval, compare the end of the day to the cursor and record one final gap if it is long enough.
The basic function
This is the version from the tutorial plan. It runs as shown.
from datetime import datetime, timedelta
def free_blocks(busy, day_start, day_end, min_length):
"""Return (start, end) gaps of at least min_length between busy intervals."""
free = []
cursor = day_start
for start, end in sorted(busy):
if start - cursor >= min_length:
free.append((cursor, start))
cursor = max(cursor, end)
if day_end - cursor >= min_length:
free.append((cursor, day_end))
return free
busy = [
(datetime(2026, 11, 30, 10, 0), datetime(2026, 11, 30, 10, 30)),
(datetime(2026, 11, 30, 13, 0), datetime(2026, 11, 30, 14, 0)),
]
gaps = free_blocks(
busy,
datetime(2026, 11, 30, 9, 0),
datetime(2026, 11, 30, 17, 0),
timedelta(minutes=90),
)
for start, end in gaps:
print(start.strftime("%H:%M"), "-", end.strftime("%H:%M"))The output is:
10:30 - 13:00
14:00 - 17:00Trace the first interval to see why 09:00 to 10:00 is missing. That gap is only 60 minutes, which is below the 90-minute minimum, so it is skipped. The cursor then moves to 10:30, where the next gap starts.
Why `max(cursor, end)` matters
Meetings overlap. If you have a 10:00 to 12:00 workshop and a 11:00 to 11:30 check-in, the second event ends before the first. Setting cursor = end would move the cursor backward to 11:30 and report a false gap. Taking the maximum keeps the cursor at 12:00.
Edge cases the basic version misses
The basic function assumes every busy interval sits inside the working day. Real calendars do not behave that way. An evening call, or an event that starts after your day ends, produces a gap that extends past day_end.
| Situation | What goes wrong | Fix |
|---|---|---|
| Busy interval starts after `day_end` | A gap is reported that runs past the end of the day | Clip the start to `day_end` |
| Busy interval ends before `day_start` | Harmless: the cursor does not move backward | None needed |
| Overlapping intervals | Handled by `max` | None needed |
| Naive and timezone-aware datetimes mixed | `TypeError` when comparing or subtracting | Make every value aware, in the same or different zones |
| All-day events | They span the whole day and can erase every gap | Filter them out, or keep only those marked busy |
| Tentative or declined events | They may count as busy when they should not | Filter by response status before calling the function |
Here is a corrected version that clips intervals to the day, plus a test that proves the fix.
from datetime import datetime, timedelta
def free_blocks(busy, day_start, day_end, min_length):
"""Return (start, end) gaps of at least min_length inside the day window."""
free = []
cursor = day_start
for start, end in sorted(busy):
start = min(start, day_end) # ignore time after the day ends
if start - cursor >= min_length:
free.append((cursor, start))
cursor = max(cursor, end)
if day_end - cursor >= min_length:
free.append((cursor, day_end))
return free
def at(hour, minute=0):
return datetime(2026, 11, 30, hour, minute)
day_start, day_end = at(9), at(17)
min_length = timedelta(minutes=90)
# An evening call must not extend the last gap past 17:00.
evening = [(at(18), at(19))]
assert free_blocks(evening, day_start, day_end, min_length) == [(at(9), at(17))]
# Overlapping meetings must not create a false gap.
overlap = [(at(10), at(12)), (at(11), at(11, 30))]
assert free_blocks(overlap, day_start, day_end, min_length) == [(at(12), at(17))]
# A fully booked day has no gaps.
full = [(at(9), at(17))]
assert free_blocks(full, day_start, day_end, min_length) == []
print("all checks passed")Time zones
The recurring block in the earlier chapter used floating time, meaning a time with no zone attached. It means 09:00 on whatever clock the viewer is using. Python's datetime objects are naive by default, and subtracting a naive value from an aware one raises TypeError. When your busy times come from a calendar export, attach a zone as you parse them:
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
tz = ZoneInfo("Europe/London")
busy = [
(datetime(2026, 11, 30, 10, 0, tzinfo=tz), datetime(2026, 11, 30, 10, 30, tzinfo=tz)),
]
day_start = datetime(2026, 11, 30, 9, 0, tzinfo=tz)
day_end = datetime(2026, 11, 30, 17, 0, tzinfo=tz)
# free_blocks is the corrected function from the previous section.Aware datetimes in different zones compare correctly, so a meeting listed in New York time still lines up with your London working hours. Be careful on the days when clocks change. A "9 to 5" day on a daylight-saving changeover is not eight hours long, and building times with tzinfo rather than adding timedeltas to a start time keeps the wall-clock meaning.
Apply your placement rules
The function finds gaps. It does not know that you do your best thinking before noon. You can encode that rule by running the function on a narrower window rather than on the whole day:
from datetime import datetime, timedelta
def free_blocks(busy, day_start, day_end, min_length):
free = []
cursor = day_start
for start, end in sorted(busy):
start = min(start, day_end)
if start - cursor >= min_length:
free.append((cursor, start))
cursor = max(cursor, end)
if day_end - cursor >= min_length:
free.append((cursor, day_end))
return free
def at(hour, minute=0):
return datetime(2026, 11, 30, hour, minute)
busy = [(at(10), at(10, 30)), (at(13), at(14))]
morning = free_blocks(busy, at(9), at(12), timedelta(minutes=90))
print(morning) # [] because 10:30 to 12:00 is exactly 90 minutes only if nothing else intrudes
anywhere = free_blocks(busy, at(9), at(17), timedelta(minutes=90))
best = max(anywhere, key=lambda gap: gap[1] - gap[0])
print(best[0].strftime("%H:%M"), "-", best[1].strftime("%H:%M"))The first call prints [(datetime.datetime(2026, 11, 30, 10, 30), datetime.datetime(2026, 11, 30, 12, 0))], because 10:30 to 12:00 is exactly 90 minutes and the comparison is >=. The second call picks the longest gap anywhere in the day and prints 14:00 - 17:00. The same approach works for "no blocks after 16:00": shrink the window.
Run the script weekly
The script fits into the weekly review from the earlier chapter. Loop over the five working days, call free_blocks for each, and print the days where no gap qualifies. Those days are where you should move a meeting, shorten one, or accept that the day is for shallow work. Treat the output as a prompt for a decision. Do not create events from it automatically, because the gaps do not account for the buffers you planned or for the meeting you are about to decline.
Limits of this approach
- The script treats all busy time as equal. It cannot tell a movable one-to-one from an unmovable client call.
- It uses a single calendar. If you have personal and work calendars, merge their busy intervals first.
- It does not write back. Creating events needs your calendar provider's API or an
.icsimport, and both need authentication that is outside this chapter.
Exercise
A day runs 09:00 to 17:00. Busy intervals are 09:30 to 11:00, 10:30 to 12:00, and 15:00 to 15:30. The minimum block length is 90 minutes. Using the corrected free_blocks, what gaps are returned?
Show answer
12:00 to 15:00 and nothing else. Trace the cursor: it starts at 09:00 and the first gap to 09:30 is only 30 minutes, so it is skipped. The cursor moves to 11:00, then the overlapping interval (10:30 to 12:00) has a start before the cursor, so no gap is recorded, and the cursor moves to 12:00. The next interval starts at 15:00, which is 180 minutes later, so (12:00, 15:00) is recorded. The cursor moves to 15:30. The final gap, 15:30 to 17:00, is exactly 90 minutes and the check uses >=, so (15:30, 17:00) is also returned. The full result is 12:00 - 15:00 and 15:30 - 17:00.
Exercise
Why does the basic version return a wrong gap when a busy interval is 18:00 to 19:00 and the day ends at 17:00, and what one-line change fixes it?
Show answer
The basic version compares the interval's start (18:00) to the cursor, so it records a gap that runs up to 18:00, past the end of the working day. Adding start = min(start, day_end) inside the loop clips the gap to 17:00.