"Days until X" sensors based on single local calendar

It’s your template sensor in your home assistant instance… you get to choose what appropriate uses of attributes are. :slight_smile:

In order to do it and minimize repeated templates, it’s better to structure it as one trigger-based sensor that gets the dates from the service call and two state-based sensors that process that into the attributes.

template:
  - trigger:
      - platform: time
        at: "00:00:00"
      - platform: homeassistant
        event: start
    action:
      - service: calendar.get_events
        data:
          start_date_time: "{{today_at()}}"
          duration:
            days: 15
        target:
          entity_id: calendar.waste_pickup
        response_variable: agenda
    sensor:
      - name: Waste Calendar Check
        state: "{{ now() }}"
        attributes:
          date_map: |
            {% set ns = namespace(types={}) %}
            {% for type in ['Recycling', 'Trash'] %}
              {% set date = (agenda['calendar.waste_pickup']['events'] | selectattr('summary', 'search', type, ignorecase=true) 
              | sort(attribute= 'start') | map(attribute='start') | map('as_datetime') | map('as_local') | first).date() %}
              {% set ns.types = dict(ns.types, **{type: date|string}) %}
            {%- endfor %}
            {{ ns.types }}

  - sensor:      
      - name: "Next Trash Pickup"
        state: "{{ state_attr('sensor.waste_calendar_check', 'date_map')['Trash'] }}"
        icon: mdi:calendar-arrow-right
        <<: &waste_attr
          attributes:
            day_of_week: "{{ strptime(this.state, '%Y-%m-%d', now()).strftime('%A') }}"
            days_until: |
              {% set event = strptime(this.state, '%Y-%m-%d', now()) %}
              {{ (event|as_local - today_at()).days }}
            countdown: |
              {% set delta = this.attributes.days_until %}
              {% if delta == 0 %} Today
              {% elif delta == 1 %} Tomorrow
              {% elif delta == 2 %} Day after Tomorrow
              {% else %} In {{ delta }} Days {% endif %}      
      - name: "Next Recycling Pickup"
        state: "{{ state_attr('sensor.waste_calendar_check', 'date_map')['Recycling'] }}"
        icon: mdi:calendar-arrow-right
        <<: *waste_attr
2 Likes