Help configuring template sensor to Calculate total "Off" time

Hey all,

I have a esphome relay (switch.relay_1_room_1) that turns on/off based on occupancy sensor readings - pretty straightforward automation.

Now, I want to know the total time for which the relay was turned off. This will help me quantify savings. See pic below for relay on/off events over 24 hrs.

What’s the best way to know the total running “Off” time for the current month? Bear in mind, occasionally when WiFi drops, the relay becomes “Unavailable” - I wouldn’t want to include unavailable times in my calculation. I was thinking of the template sensor but I honestly have no idea where to begin since I’m not too proficient with the coding bit.

Thanks a lot for your help.

Take a look at the History Stats helper.

You can configure it from the GUI, which makes it somewhat easier. You basically pick the entity to track (switch.relay_1_room_1) and the state you want to track (off) and set it as a time thing. You set when it starts (at the beginning of the month) and for how long to goes (or when it should end). I found the bounds of the measurement to be the trickiest part.

1 Like

One thing to keep in mind is that the History Stats integration uses the stored states in the recorder to recalculate the value after a home assistant restart. By default the recorder only keeps ten days of state data. So if you want a monthly total then you will have to adjust the recorder purge_keep_days option to 31. Do not be tempted to increase it much beyond this or HA may suffer performance issues.

Also in the History Stats config make sure to follow the state 'off' not off (i.e. use quotes). They are different things. The first is a string (and states are strings) the second is a boolean value.

Fortunately there is an example in the documentation you linked to for a monthly range:

start: "{{ today_at('00:00').replace(day=1) }}"
end: "{{ now() }}"
1 Like

So if you want a monthly total then you will have to adjust the recorder purge_keep_days option to 31

Noted. Thanks.

start: “{{ today_at(‘00:00’).replace(day=1) }}”
end: “{{ now() }}”

This should do it I think as it represents a running count from the start of the month.

I’m going through the History Stats configuration documentation - I’m not sure if I should be installing the integration as well as doing the yaml config. to get this going. If I just do the yaml config., that should work, right?

Thanks.

Nevermind. I got this running.

Thanks!

1 Like