Getting How Long an Entity Has Been in the Previous State

I have an automation which records (to a text file) each time my boiler’s burner state changes (on or off.)

I use this data outside HA from time to time to calculate various things. The first step is always to calculate how long it lasted, each time the burner was “on.”

Obviously the automation is able to access the from_state and to_state. What I want to know is how long the entity had remained in the “from” state before the state change. In other words, how long since the last time the state changed (which would also be how long since the last time this trigger fired, if that helps.)

Any ideas on how to do this in HA, so I don’t have to do it later, when I go to analyze the data?

1 Like

from_state / to_state contain last_changed, so

{{ trigger.to_state.last_changed|as_timestamp - trigger.from_state.last_changed|as_timestamp }}

Gives you the time in seconds between the previous change and the current one.

2 Likes

Thanks, I got two possible solutions right away!!

I didn’t know there was a last_changed time associated with both the from_state and to_state. That seems like the most straightforward way to go. For the record, my automation now does this to write to the text file:

  trigger:
  - entity_id: binary_sensor.boiler_burner
    platform: state
  action:
  - data_template:
      message: "{{ now().strftime('%x') }} {{ now().strftime('%X') }}\tBurner {{ trigger.to_state.state }}\t{{ ((trigger.to_state.last_changed|as_timestamp) - (trigger.from_state.last_changed|as_timestamp)) | timestamp_custom('%H:%M:%S',0) }}"
    service: notify.burnerlog

And here’s an example from the output (the text file):

11/26/21 12:04:28   Burner on   00:11:11
11/26/21 12:08:54   Burner off  00:04:25|
4 Likes

Update: data_template: has been deprecated, and the whole notify to a file thing has changed. This is what I think I’ll need to do when I update to 2024.6.x:

  trigger:
  - entity_id: binary_sensor.boiler_burner
    platform: state
  action:
  - service: notify.send_message
    target: 
      entity_id: notify.burnerlog
    data:
      message: "{{ now().strftime('%x') }} {{ now().strftime('%X') }}\tBurner {{ trigger.to_state.state }}\t{{ ((trigger.to_state.last_changed|as_timestamp) - (trigger.from_state.last_changed|as_timestamp)) | timestamp_custom('%H:%M:%S',0) }}"
        -> {{trigger.topic}} - {{ trigger.payload_json}}'
OR

  action:
  - service: notify.send_message
    data:
      entity_id: notify.burnerlog
      message: "{{ now().strftime('%x') }} {{ now().strftime('%X') }}\tBurner {{ trigger.to_state.state }}\t{{ ((trigger.to_state.last_changed|as_timestamp) - (trigger.from_state.last_changed|as_timestamp)) | timestamp_custom('%H:%M:%S',0) }}"