Sub topic 14
Automate recurring blocks and find free time with code
This chapter assumes you already keep a digital calendar and can create recurring events. It also assumes you have an ideal-week template (the previous chapter's topic). Here you will turn that template into files a calendar can import. You will also write a small script that finds open time in a day and places tasks into it.
What is worth automating
Automate the parts of time blocking that are mechanical and repeated:
- Recurring blocks that never change, such as a daily focus block, a weekly review, or a lunch break.
- Finding gaps between meetings so you can place tasks.
- First-pass placement of estimated tasks into those gaps.
Do not automate decisions about priority or energy. Those belong to your daily planning ritual. A script that places tasks should give you a draft that you adjust, not a final plan.
Recurring blocks as an iCalendar file
iCalendar (the .ics format, defined in RFC 5545) is a plain-text format that Google Calendar, Outlook, and Apple Calendar can all import. One VEVENT with a recurrence rule (RRULE) can produce hundreds of blocks.
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example//Time Blocking//EN
BEGIN:VEVENT
UID:[email protected]
DTSTAMP:20260101T080000Z
DTSTART:20260105T090000
DTEND:20260105T103000
RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR
SUMMARY:Focus block: deep work
TRANSP:OPAQUE
END:VEVENT
END:VCALENDARThis creates a 90-minute block every weekday at 09:00, starting Monday 5 January 2026. The fields that matter:
| Field | Purpose |
|---|---|
| `UID` | A globally unique ID. Re-importing the same UID updates the event instead of duplicating it. |
| `DTSTAMP` | When the record was created, always in UTC (the trailing `Z`). |
| `DTSTART` / `DTEND` | First occurrence. `DTEND` minus `DTSTART` is the length of every occurrence. |
| `RRULE` | The repetition rule. `BYDAY` lists the weekdays. |
| `TRANSP` | `OPAQUE` shows you as busy. `TRANSPARENT` shows you as free. |
Floating time versus fixed time
DTSTART:20260105T090000 has no Z and no time zone. This is floating time: the block is 09:00 on whatever clock the importing calendar uses. That is what you want for a personal focus block, because it stays at 09:00 when you travel.
If you want a block pinned to a place, use DTSTART;TZID=Europe/London:20260105T090000. If you write it in UTC (...T090000Z), the block stays at the same instant. In a region with daylight saving time, the local start then shifts by an hour when the clocks change. For recurring local-time blocks, this is a common source of blocks that drift.
Common errors with `.ics` files
- Each line should end with CRLF (carriage return plus line feed). Some strict parsers reject files with bare line feeds.
- Lines longer than 75 bytes should be folded onto a continuation line that starts with a space. Long
DESCRIPTIONtext is where this usually matters. - Importing creates a copy in the calendar you pick. Check that you chose the right calendar, so the blocks do not end up in a shared team calendar.
- Importing the same file twice with a different
UIDcreates duplicates. Keep UIDs stable and unique per block. - To stop a series on a date, add
UNTIL=20261231T235959to theRRULE, or useCOUNT=for a fixed number of occurrences. Without either, the series never ends.
Finding free slots
Once your fixed meetings are in the calendar, the next question is where the gaps are. The function below takes a workday and a list of meetings, then returns the free intervals. It sorts the meetings by start time and keeps a cursor at the end of the busy time seen so far.
from datetime import datetime
def free_slots(day_start, day_end, busy):
slots = []
cursor = day_start
for start, end in sorted(busy):
if start > cursor:
slots.append((cursor, start))
cursor = max(cursor, end)
if cursor < day_end:
slots.append((cursor, day_end))
return slots
day_start = datetime(2026, 1, 5, 9, 0)
day_end = datetime(2026, 1, 5, 17, 0)
busy = [
(datetime(2026, 1, 5, 13, 0), datetime(2026, 1, 5, 14, 0)),
(datetime(2026, 1, 5, 10, 0), datetime(2026, 1, 5, 10, 30)),
]
for start, end in free_slots(day_start, day_end, busy):
print(start.strftime('%H:%M'), '-', end.strftime('%H:%M'))
# 09:00 - 10:00
# 10:30 - 13:00
# 14:00 - 17:00Two details make this correct:
- The input is sorted, so the busy list can arrive in any order. The second meeting in the example is listed first and the function still works.
cursor = max(cursor, end)handles overlapping and nested meetings. If a 10:00-12:00 meeting contains a 10:30-11:00 meeting, the cursor does not move backwards.
A gotcha: meetings outside the workday
The version above assumes every meeting falls inside the workday. A meeting that starts after day_end would produce a free slot that runs past the end of the day. Clip each meeting to the workday and skip the ones that end up empty.
Placing tasks into the gaps
With free slots in hand, a first-fit placement gives a draft plan. For each task, the script looks for the first slot that can hold the task plus a buffer, which is the padding you chose in the buffers chapter. It then shrinks that slot by the amount used.
This script is self-contained. It includes the clipped version of free_slots.
from datetime import datetime, timedelta
def free_slots(day_start, day_end, busy):
slots = []
cursor = day_start
for start, end in sorted(busy):
start, end = max(start, day_start), min(end, day_end)
if end <= start:
continue
if start > cursor:
slots.append((cursor, start))
cursor = max(cursor, end)
if cursor < day_end:
slots.append((cursor, day_end))
return slots
def place_blocks(slots, tasks, buffer=timedelta(minutes=10)):
remaining = list(slots)
plan = []
for name, length in tasks:
need = length + buffer
for i, (start, end) in enumerate(remaining):
if end - start >= need:
plan.append((name, start, start + length))
remaining[i] = (start + need, end)
break
else:
plan.append((name, None, None))
return plan
day_start = datetime(2026, 1, 5, 9, 0)
day_end = datetime(2026, 1, 5, 17, 0)
busy = [
(datetime(2026, 1, 5, 10, 0), datetime(2026, 1, 5, 10, 30)),
(datetime(2026, 1, 5, 13, 0), datetime(2026, 1, 5, 14, 0)),
(datetime(2026, 1, 5, 18, 0), datetime(2026, 1, 5, 19, 0)),
]
tasks = [
("Draft report", timedelta(minutes=90)),
("Review pull requests", timedelta(minutes=30)),
("Plan sprint", timedelta(minutes=60)),
("Write proposal", timedelta(hours=4)),
]
slots = free_slots(day_start, day_end, busy)
for name, start, end in place_blocks(slots, tasks):
if start is None:
print(name, "- not placed")
else:
print(name, start.strftime('%H:%M'), '-', end.strftime('%H:%M'))
# Draft report 10:30 - 12:00
# Review pull requests 09:00 - 09:30
# Plan sprint 14:00 - 15:00
# Write proposal - not placedNotice what the output tells you. "Draft report" is placed first in the list, but it lands later in the day than "Review pull requests" because the 09:00 slot is only 60 minutes long. "Write proposal" does not fit anywhere, which is useful information: the day is overcommitted, and you must split the task, move it to another day, or drop something.
Limits of first-fit
First-fit is a draft, not an optimizer. Know where it falls short:
- It ignores energy. A deep-work task can land in your low-energy afternoon. Sort tasks by priority and restrict deep-work tasks to deep-work slots before calling it.
- It ignores task order and dependencies.
- It never splits a task. A 4-hour task needs a 4-hour gap, or you must split it into smaller blocks yourself.
- It places buffers after tasks only. A buffer before the first block in a slot is not modeled.
Getting real meetings into the script
The examples hard-code the meeting list. To use your real calendar, you need a source of busy intervals:
- Export a
.icsfile from your calendar and parse it with a library such asicalendar. Recurring events must be expanded into occurrences for the day you care about, which a library such asrecurring-ical-eventscan do. - Use a calendar API. Google Calendar offers a free/busy query that returns busy intervals for a time range, and Microsoft Graph offers a similar schedule lookup. Both need authorization, so keep credentials out of your code and out of version control.
Whatever the source, convert every interval to the same time zone type first. Python raises a TypeError if you compare a naive datetime (no time zone) with an aware one.
When automation stops paying off
Automation has a cost: maintenance. A recurring .ics import saves time for blocks that stay fixed for months, such as a daily shutdown or a weekly review. A script that places tasks saves time only if you plan many tasks per day. If you plan five or fewer, dragging blocks by hand during your five-minute daily planning is faster than keeping code running.
Exercise
A meeting list for one day is [(14:00, 15:00), (09:30, 10:30), (10:00, 11:00)] and the workday is 09:00 to 17:00. Using the first version of free_slots from this chapter, what slots are returned, and why does the overlap between the second and third meetings not break the result?
Show answer
The slots are 09:00-09:30, 11:00-14:00, and 15:00-17:00. After sorting, the meetings are 09:30-10:30, 10:00-11:00, 14:00-15:00. The first meeting leaves a gap from 09:00 to 09:30 and moves the cursor to 10:30. The second meeting starts at 10:00, which is not after the cursor, so no slot is added, and the cursor becomes max(10:30, 11:00) = 11:00. The cursor only moves forward, so overlapping meetings are merged into one busy stretch.
Exercise
You import an .ics file with a daily 09:00 block written as DTSTART:20260105T090000Z, and you live in a region that changes its clocks in spring. What happens to the block in your calendar after the change, and how do you fix the file?
Show answer
The trailing Z makes the time UTC, so the block stays at the same instant. In local time it shifts by an hour after the clock change, for example from 09:00 to 10:00. To keep it at 09:00 local time, remove the Z to use floating time, or use DTSTART;TZID=Your/Zone:20260105T090000 with your own time zone name.