Time between last state change and the one before that


I would like to obtain time between a sensor changed values the last two times. I can not figure out how I should do it. Any help would be appreciated. I have included a picture to illustrate which data I would like to extract.

You can use a pair of SQL sensors to get the times:

  - platform: sql
      - name: hottub_temp_last_changed
        query: "SELECT last_changed FROM states WHERE entity_id = 'sensor.hottub_pump_temp' ORDER BY created DESC LIMIT 1;"
        column: "last_changed"
        value_template: "{{ as_timestamp(value~'+00:00') | timestamp_local }}"
      - name: hottub_temp_last_changed_2
        query: "SELECT * FROM (SELECT * FROM states WHERE entity_id = 'sensor.hottub_temp_last_changed' ORDER BY state_id DESC LIMIT 2) two_entity ORDER BY state_id ASC LIMIT 1;"
        column: "state"

I’m not clear if you just wanted the times or you were trying to get the difference between those two… for that you would use a state-based template sensor based on the sensors above:

  - sensor:
      - name: "Hot Tub temp sample time"
        state: >
          {{  states('hottub_temp_last_changed')|as_datetime -
          states('hottub_temp_last_changed_2')|as_datetime }}

Thanks a lot. Exactly what I was looking for.