Show how long a switch was on


how can I display the time how long a switch was in the state on

Use the secondary info option in many cards.

You can use the History Stats integration to create a sensor that monitors the switch and records how long the switch’s state is on (minutes/hours/days). You can then display the History Stats sensor in the UI.

1 Like

So many ways to do things with HA. I use a template sensor to see how long since my HVAC has been either running or not running. Simply compares the time now to the time a sensor was last_changed and formats to my liking.

      value_template: >
        {% set elapsed = (as_timestamp(states('sensor.date_time').replace(',','')) - as_timestamp(states.sensor['6900_kitchen_hvac_action'].last_changed| default(0)) | int ) %}
        {% set days = (elapsed / 86400) | int %}
        {% set hours= ((elapsed  % 86400) / 3600) | int %}
        {% set mins = ((elapsed  % 3600) / 60) | int %}
        {% set secs = elapsed | int % 60 %}
        {% if days > 0 %} {{days}}d {%if hours < 10 %}0{%endif%}{{hours}}:{%if mins< 10 %}0{%endif%}{{mins}}
        {% elif hours > 0 %} {% if hours < 10 %}0{%endif%}{{hours}}:{%if mins< 10 %}0{%endif%}{{mins}}
        {% elif mins > 0 %} {{mins}}m
        {% else %} {{secs}}s {% endif %}
1 Like

I solved it that way:

  - platform: history_stats
    name: heater-on-time
    entity_id: binary_sensor.heater-state
    state: 'on'
    type: time
    start: '{{ now().replace(month=1, day=1, hour=0, minute=0, second=0) }}'
    end: '{{ now() }}'

This solution displays the time since 01.01. of the current day

1 Like

I’m glad to hear that the use of History Stats helped solve the problem.

For future reference, it’s the community’s custom to assign the Solution tag to the first post that offers, or leads to, the solution.

By marking your own post with the Solution tag, it gives the impression you formulated the answer without anyone’s assistance. If everyone who asks a question proceeds to mark there own post as the solution it gives the misleading impression everyone eventually solves their own problems.

history_stats unfortunately has a very coarse resolution - 0.01h (100th of an hour) is the smallest interval it can measure and that is 36 seconds.