Fix Template Sensor Error when Attribute Unavailable

I have the below sensor that is giving an error because the start_time attribute is not present when there is not an event in the calendar. I realize that { else } will not work as I have it currently. Is there a way to adjust this so that it will return “No games scheduled” when the sensor is “off” and start_time attribute does not exist?

          {% if is_state('calendar.detroit_tigers',"on") %}
            Playing Now
          {% elif is_state('calendar.detroit_tigers',"off") %}
            {{ as_timestamp(states.calendar.detroit_tigers.attributes.start_time)  | timestamp_custom("%A, %b %d at %-I:%M %p") }}
          {% else %}
            No games scheduled
          {% endif %}

I’ve got something similar that might help

    date_now_gcisd:
      entity_id: sensor.date
      value_template: >
        {% if states('calendar.calendar') == 'off' %}
          off
        {% elif now().timestamp() >= as_timestamp(strptime(states.calendar.calendar.attributes.start_time, '%Y-%m-%d %H:%M:%S')) and now().timestamp() <= as_timestamp(strptime(states.calendar.calendar.attributes.end_time, '%Y-%m-%d %H:%M:%S'))  %}
          on
        {% else %}
          off
        {% endif %}

I see what yours is doing. I am not sure what to take from it to fix my issue. My first two lines work fine, just not sure how to fix the error when there is no calendar event.

          {% if is_state('calendar.detroit_tigers',"on") %}
            Playing Now
          {% elif is_state('calendar.detroit_tigers',"off") %}
            {% set st = state_attr('calendar.detroit_tigers', 'start_time') %}
            {% if st != None %}
              {{ as_timestamp(st)  | timestamp_custom("%A, %b %d at %-I:%M %p") }}
            {% else %}
              No games scheduled
            {% endif %}
          {% else %}
            No games scheduled
          {% endif %}

I’m unfamiliar with the valid states for calendar. If it’s only either on or off then your template can be reduced to this:

          {% if is_state('calendar.detroit_tigers', 'on') %}
            Playing Now
          {% else %}
            {% set st = state_attr('calendar.detroit_tigers', 'start_time') %}
            {% if st != None %}
              {{ as_timestamp(st)  | timestamp_custom("%A, %b %d at %-I:%M %p") }}
            {% else %}
              No start time
            {% endif %}
          {% endif %}

This worked perfectly!!! I learn more about templating each day. Thanks

1 Like