Trigger Automation Based on Calendar events

Hello, I am trying to create an automation whereby it triggers at 9am and checks my calendar to see if I have any events scheduled within a 2 hour time frame. If not, it will notify me via phone app to go for a walk, if so nothing will happen. Based on some posts I have seen and doing some reseach here is the code I came up with but it always renders “false” even when I have no events on the calendar. Any help would be greatly appreciated!

alias: "Trigger if Calendar is Free Between 9 AM and 11 AM"
description: "This automation triggers only if there are no calendar events between 9 AM and 11 AM."
trigger:
  - platform: time
    at: "09:00:00"  # Start at 9 AM
condition:
  - condition: template
    value_template: >
      {% set start_time = now().replace(hour=9, minute=0, second=0, microsecond=0).timestamp() %}
      {% set end_time = now().replace(hour=11, minute=0, second=0, microsecond=0).timestamp() %}
      {% set event_start = as_timestamp(state_attr('calendar.d', 'start_time')) %}
      {% set event_end = as_timestamp(state_attr('calendar.d', 'end_time')) %}
      
      # If the event's start or end time overlaps with the window between 9 AM and 11 PAM, calendar is busy.
      {{ (event_start is none or event_start > end_time) and 
         (event_end is none or event_end < start_time) }}
action:
  - service: notify.ds_iphone
    data:
      message: "No calendar events between 9 AM and 11 AM. Time to take a walk!"
mode: single

One issue might be the way you are commenting… In a template block, comments need to be surrounded by comment delimiters {# #}.

However, the method you have chosen will be unreliable if the calendar has overlapping events (including all-day events). A more reliable method would be to use the calendar.get_events action to query the calendar for events in the desired time span.

alias: "Trigger if Calendar is Free Between 9 AM and 11 AM"
description: "This automation triggers only if there are no calendar events between 9 AM and 11 AM."
trigger:
  - platform: time
    at: "09:00:00"  # Start at 9 AM
condition: []
action:
  - action: calendar.get_events
    target:
      entity_id: calendar.d
    data:
      start_date_time: "{{ today_at('9:01') }}"  #Offset prevents including events that end at 9:00
      end_date_time: "{{ today_at('10:59') }}"
    response_variable: agenda
  - alias: Check that no events are included in the returned agenda of events (exclude all-day events)
    condition: template
    value_template: |
      {{ not agenda['calendar.d']['events'] | selectattr('start', 'search', ':')
      | list | count | bool  }}
  - service: notify.ds_iphone
    data:
      message: "No calendar events between 9 AM and 11 AM. Time to take a walk!"
mode: single

That totally did it. Thank you so much! Much appreciated.