Creating a sensor for consumption from battery level

I have a sensor for the battery level of an E-Car “”. How can I calculate just consumption out of this and exclude charging of the battery? I tried several codes like this:

{% set current_bs = states('') | float %}
{% set previous_state = %}
{% set previous_bs = | float if previous_state else 0 %}
{% set consumption = 0 %}
{% if previous_state %}
     {% set consumption = previous_bs - current_bs if current_bs < previous_bs else 0 %}
{% endif %}
{{ consumption | round(0) }}

The result is always 0. Thanks for your support.

Nobody here who can support? Thanks,

I’m assuming is the energy level of the battery in kWh? If it is a percentage the math will be a little different.

I think the easiest way would be to first make a template sensor (can be done in the UI) that is simply the sensor value subtracted from the battery size. For a 50 kWh battery it would be {{ 50 - states('') | float(50) }}

Then you can create a utility meter helper (also in the UI) using your new template sensor as the source. Make sure net metering is disabled, this will allow it to ignore charging.

Thanks, I’ll try.

It worked, thanks.