Last Updated info is being reset after HA starts

Hi all,

Can you please help me? :grinning:

I have a switch which stays ON only for 1 seconds and then goes OFF automatically.

I need to calculate the time difference between “now” and “the time it went ON”. So I can write it as info on the cards. For example: “34 minutes ago”

I managed it with below code but every time HA restart timer is reset to HA start time. I want it to show always delta from the last time the switch was ON, not the delta from HA starts.

template:

  - trigger:

      - platform: state

        entity_id: switch.driveway

        to: 'on'

    sensor:

      - name: driveway_on

        state: "{{ now().timestamp() | timestamp_custom('%I:%M %p %a') }} "

Card info

{{ relative_time(states.sensor.driveway_on.last_changed) }}

Thanks.

Because the sensor gets triggered by every from state to on.


trigger:

      - platform: state
        entity_id: switch.driveway
        from: 'off'
        to: 'on'

should avoid this.

I believe some have a boolean “restore” property meant for this - could be that

Thanks but that didn’t work

What exactly did not work?

Alternatively, you can add


not_from:
- unavailable 
- unknown
- none
- null

P.S.: You mentioned 2 sensors, sensor.driveway_on and sensor.light_on. Do they follow the same structure?

I have 1 sensor. Sorry for the typo. I fixed it.

It didn’t work because, when HA starts, It updated the sensor not the state of switch. So “states.sensor.driveway_on.last_changed” is always equals to HA start time. I need to solve this but How?

Somehow, I need to write somewhere the time “the switch goes ON”, then minus from now. And “time the switch goes ON” should not be overwritten when HA restarts.

Note: default state of switch is OFF

The state of the sensor should catch the real last change of your switch (but I highly recommend to add a from state to the trigger).

Solution:

Config yaml

template:
  - trigger:
      - platform: state
        entity_id: switch.driveway
        from: "off"
        to: 'on'
    sensor:
      - name: driveway_on
        state: "{{ now().timestamp()}}"

Card info

{{ relative_time(states.sensor.driveway_on.state | as_datetime)

@pedolsky Thank you mate!