Template sensor - filter drops to zero

Hello probably already answered somewhere but quick search doesn’t came up with anything obvious.
I have smart zigbee plug. Its working fine, but from the begging its has strange behavior (i guess its common with those cheap plugs) that every 5 minutes or so power reading drops to zero for about 5 seconds.

Its not a big problem, power consumption is calculated correctly but it destroys the graphs :slight_smile:

And since the devices that are connected to that plug ale not constantly running , so i cannot filter all zero values.
I already know how to filter values that are greater than certain value , but how to filter all zero values that are no longer that let say 10 sec in the row and replace it with previous non zero values ?

First check if the integration you are using to bring that plug into HA has any settings that can be adjusted to address the issue. The integration is responsible for that entity and you are at the mercy of whatever functionality it offers, if you want to fix that problem at the source.

The next option is to create a new entity that uses some logic to filter out those dropouts. However the problem here is that everything is done live rather looking backwards at historical data. So you would use logic like “if source sensor is 0, use the previous good data point, but when the source sensor has been 0 for more than 10 seconds start using 0.” With this type of logic, when the device is turned off on purpose, you won’t see the power drop to zero until 10 seconds later. You can use a template sensor to manually code that logic yourself using jinja templates, or you can use an integration like the filter integration to filter it.

Your final option is to just edit the historical data in the recorder database, if all you care about is having pretty graphs. You’d have to do this with SQL commands and those commands are dependent on the database you are using (SQLite, MariaDB, etc).