How long switch has been on for?

Try the following Template Sensor. You will need to define sensor.time using the Time & Date integration.

  - platform: template
    sensors:
      coffee_time:
        entity_id:
          - sensor.time
          - switch.coffee
        value_template: >
          {% set t = 0 if states('switch.coffee') == 'off' else now().timestamp() - states.switch.coffee.last_changed.timestamp() %}
          {{ t | timestamp_custom('%H:%M', false) }}

The sensor’s template will be evaluated whenever sensor.time changes state (every minute) or switch.coffee changes state (on or off). It simply subtracts the switch’s last_changed from the current time (but only if the switch is currently on, otherwise it simply reports 0). The result is a time value in seconds which is converted so it appears in HH:MM format.


EDIT
Corrected typo in template’s last line.

1 Like