Get timestamp of last time when binary sensor was in off state for certain duration


I have a Xiaomi air humidifier, which for obvious reasons needs to be cleaned regularly.
I have a binary_sensor which tells me if the water tank is attached or not.

I want to create a sensor that tells me the timestamp of the last time when the water tank was NOT attached (in off state) for more than 2 minutes → indicating the last time I have cleaned it.

I am new to history stats and templating and am struggling with this.

What I have right now is just the last time the state has changed, which is not very helpful because it might be that we take off the water tank when refilling, but this does not last more than 2 minutes.

Quick and dirty (trigger-based template sensor):


  - trigger:
      - platform: state
        from: 'on'
        to: 'off'
          minutes: 2
          seconds: 1
      - name: Test
        unique_id: '202210111758'
        state: |
          {% set time = now().strftime('%T') %}
          {{ time }}
        icon: mdi:ab-testing
          filepath: /packages/sensoren/testsensoren.yaml


Ah I see, I tried to tackle it from the wrong end. I was looking for a solution to analyze the history, but it is enough to define a trigger, which saves the current time when it is triggered.

Got it working, thanks!