Create template sensor that calculates ev efficiency daily

Hi I am trying to create a sensor to calculate my daily ev efficiency. I have daily numbers for kwh used and miles so I just need to divide the 2 daily.

I tried doing it this way but the value returns this:

image

Ideally it would do this calculation once a day at the end of the day.

Tried messing with automations and time triggered templates but have not really had any luck.

If anyone could assist in getting this to work I’d greatly appreciate it.

Your template is straightforward, it simply divides two numbers and rounds the result.

{{ ((states('sensor.test_tesla_daily_mileage') | float) /
  (states('sensor.tesla_model_3_daily_energy_used')|float)) | round(2) }}

However, it doesn’t guard against the possibility that the divisor can be zero. When it attempts to divide a number by zero, the result is an error message:

image

Try this version. It reports 0 if the daily energy use is 0 otherwise it performs the division.

  {% set mileage = states('sensor.test_tesla_daily_mileage') | float(0) %}
  {% set energy = states('sensor.tesla_model_3_daily_energy_used') | float(0) %}
  {{ 0 if energy == 0 else (mileage / energy) | round(2) }}

In that case, you will need to create a Trigger-based Template Sensor (not a Template Sensor helper). Currently, trigger-based Template entities can only be defined via YAML, not the UI.

Example:

template:
  - triggers:
      - trigger: time
        at: '23:59:00'
    sensor:
      - name: Whatever you want to call it
        state: >
          {% set mileage = states('sensor.test_tesla_daily_mileage') | float(0) %}
          {% set energy = states('sensor.tesla_model_3_daily_energy_used') | float(0) %}
          {{ 0 if energy == 0 else (mileage / energy) | round(2) }}
        unit_of_measurement: mi/kWh
        state_class: measurement

Thank you I was able to get the time based trigger working the way I wanted based on your example.

1 Like

You’re welcome!

Before you go, please consider marking my post above with the Solution tag. It helps other users find answers to similar problems.