Up-voted. This would be nice. There are kludgy ways around it (like most things). FWIW I use hass-variables (https://github.com/rogro82/hass-variables) and some automations and sensors for this.
Our front gate is an example.
variable.yaml:
front_gate_open:
value: '0'
restore: true
I have to create template switch for some of my entities that I want to track that triggers scripts to turn them on so I can set the variable (suppose I could also do this with an automation listening for the ‘to: on’ state change…
switches.yaml
- platform: template
switches:
front_drive_gate:
friendly_name: "Front Driveway Gate"
value_template: "{{ is_state('binary_sensor.front_gate_contact', 'on') }}"
turn_on:
service: script.front_gate_open
turn_off:
service: script.front_gate_close
icon_template: "mdi:gate"
The key here is when the gate is OPENED the scripts sets the variable as now().timestamp()
scripts.yaml
front_gate_open:
sequence:
- condition: state
entity_id: binary_sensor.front_gate_contact
state: 'off'
- service: switch.turn_on
entity_id: switch.front_gate
- service: variable.set_variable
data:
variable: front_gate_open
value_template: "{{ now().timestamp() }}"
I then created a sensor to display amount of time since last open. Certainly many ways to display this time, it’s how I choose to do it.
sensors.yaml
front_gate_last_open:
value_template: >
{% set elapsed = (as_timestamp(states('sensor.date_time').replace(',','')) - states('variable.front_gate_open') | 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 %}
I then have a conditional card in my UI that shows how long the gate has been open, and survives restarts.
ui-lovelace.yaml
- type: conditional
conditions:
- entity: binary_sensor.front_gate_contact
state_not: "off"
card:
type: entities
style: |
ha-card #states {
margin-bottom: -5px !important;
padding-top: 5px !important;
padding-bottom: 0px;
}
entities:
- entity: switch.front_drive_gate
type: custom:multiple-entity-row
name: Front Gate
state_color: true
toggle: false
show_state: false
entities:
- entity: switch.front_drive_gate
toggle: true
name: false
tap_action:
action: call-service
service: script.turn_on
service_data:
entity_id: script.front_gate_close
- entity: sensor.front_gate_last_open
name: Duration
Which displays this when it’s open:
Always a bunch of ways to skin a cat in HA, but this is certainly a round-about method to do it. (I understand I could create automation to remove some of these steps - but hey, I coded it a year ago and am too lazy to change [if it ain’t broke, don’t fix it]).