Recover daily time calendar data

Hello everyone :slight_smile:

As part of my system, I want to retrieve the daily action time of an event in the calendar (time between START and END during the day).

Today, I created a simple sensor in the config file, which counts the time of this event during the day:

  - platform: history_stats
    name: "Temps filtration prƩvu planning"
    entity_id: calendar.filtration
    state: "on"
    type: time
    start: "{{ now().replace(hour=0, minute=0, second=0) }}"
    end: "{{ now().replace(hour=23, minute=59, second=59) }}"

The problem is that this element counts the time spent cumulatively at the current moment:
188105fb5e58a71fdaa53363ba24d7012742ed74

What I want is for it to tell me the cumulative time planned in the schedule for the entire day of the current day.
In my concrete case today, let me recover the time for the ā€œfiltrationā€ subject in the schedule indicated today:

f6d3c0da159bc608d9e01d411f47d72176e5355a

So basically currently, I do not have the forecast time which was recorded in the schedule, but ā€œthe time spent at the moment Tā€ of this event.
Here, I would therefore like it to be indicated ā€œ12Hā€ (that it calculates the difference between the start and end of ā€œfiltrationā€ during the day, here start 3h to end 5h = 2 and from start 10h to end 20h = 10, so total time=12h).

Is this possible?

You will need to use a trigger-based Template sensor with the calendar.get_events action:

template:
  - trigger:
      - platform: time
        at: "00:00:00"
    action:
      - action: calendar.get_events
        target:
          entity_id: calendar.filtration
        data:
          start_date_time: "{{ today_at('00:01:00') }}"
          end_date_time: "{{ today_at('23:59:00') }}"
        response_variable: agenda
    sensor:
      - name: Scheduled Filtration Duration
        state: |
          {% set ns = namespace(durations=[])%}
          {% for event in agenda['calendar.filtration']['events'] %}
            {% set ns.durations = ns.durations + [(event.end | as_datetime - event.start | as_datetime).total_seconds()] %}         
          {% endfor %}
          {{ ns.durations | sum / 3600 }}
        unit_of_measurement: hours

okā€¦
I would never have foundā€¦
So I have also to create the ā€˜Scheduled Filtration Durationā€™ sensor as a digital entity?

Yes, just make sure to set it up with triggers that make sense for your needs. As configured above it will only run at the start of each day. If you add or remove events from the calendar during the day that need to be accounted for, you can use a Time Pattern or Calendar Event trigger.

okā€¦ great!
Iā€™ll try to do that and let you know the results!
anyway thank you :slight_smile: