Tracking time an input boolean is set to on

Hi! I have searched the internet for two days and two nights, to no avail.

I have an input boolean “input_boolean.3d” that is triggered to “on” from node red whenever my 3d-printer starts printing, and subsequently turned to “off” whenever my printer finishes.

I would like to track the total time of the current cycle the printer has been active, and reset it to zero when it’s turned off, so that it only counts time each time it’s on, from zero. I have only managed to get it to track total time using history.

Does anyone have any solutions?

Template sensor, which you can create from the UI. State template:

{{ (now() - states['input_boolean.3d']['last_changed'])
   if is_state('input_boolean.3d', 'on') else "0"|as_timedelta }}

The different types of brackets are correct. I’d recommend not starting an entity ID with a digit (e.g. 3d) as you may find problems later on. For example, you might read other posts and try to use something like:

{{ states.input_boolean.3d.state }}

but that will fail with an entity ID that starts with a digit.

1 Like

You are an absolute saint. This worked just as I needed it to. Thank you for the tip as well. Entity has been renamed

1 Like

Is there an easy way to format this as HH:MM?

{% set s = ((now() - states['input_boolean.YOUR_ID']['last_changed'])
   if is_state('input_boolean.YOUR_ID', 'on')
   else "0"|as_timedelta).total_seconds() %}
{% set h, s = s//3600, s%3600 %}
{% set m, s = s//60, s%60 %}
{{ "%02d:%02d" % (h, m) }}

Also you can make automation with trigger:

platform: state
  - sensor.some_sensor
from: "on"
to: "off"

and have this code in it to calculate duration:

{{ (as_timestamp(trigger.to_state.last_changed) - as_timestamp(trigger.from_state.last_changed)) | timestamp_custom("%H:%M:%S", false) }}

Thank you both for your replies. This helped immensely and I learned a new thing or two.

Perfect @Troon @WildRat solution for monitoring how long my water pump is on for and running automation if it overruns. Thank you