Time Sensor showing as Unknown, but data is correct

I have a ‘Battery Time Remaining’ sensor I created to give an estimate of house battery charge. In the Template section of Dev Tools I can see that the code works and returns an hr:min format.

However, as an Entity, it returns/displays only ‘Unknown’ as the result.
I’m relatively new to HA, so I’ve very likely i’ve done something silly or just missed something altogether.

Any advice would be most welcome.

Thanks for all the help I’ve already received by reading other’s posts

Here’s the code directly from the configuration.yaml file:

  - sensor:
      - name: "Battery Time Remaining"
        unit_of_measurement: "Hr"
        state: >
          {% set percent = states('sensor.batt_average_soc') | float(0) / 100.0 | float(0) %}
          {% set number = 2 | float(0) %}
          {% set energy = 5 | float(0) %}
          {% set reserve = (20 | float(5)) / 100.0 %}
          {% set charge = ((percent - reserve) * number * energy) | float(0) %}
          {% set a = states('sensor.Battery_Charge_Power') | float(0) / 1000 %}
          {% set current_power = a %}
          {% set decimal_hours = charge / current_power %}
          {% set minutes = (decimal_hours % 1 * 60) | round(0) %}
          {{ '{:2}:{:02}'.format(decimal_hours | int(00), minutes | int(00)) }}

??? a sensor’s id with capitals?

I’ve updated it to be all lower case, but it didn’t throw any errors with the caps.

What is “it”? Dev tools? It may not throw errors - but the template sensor will be undefined…

‘it’ was the Dev Tool Template simulator. It’s given me errors for any other mistake, I think.
I’ve changed it now anyway and same issue. The Template preview shows Hr:Min return, but the sensor itself is ‘Unknown’.

Remove this line from the sensor’s configuration:

unit_of_measurement: "Hr"

If you include unit_of_measurement then it expects the sensor’s value to be numeric. However, in your case, it’s not numeric but a string in this format 6:40 and that’s why it reports unknown.

1 Like

Not related to the main issue:
I also wonder what is a meaning of using “float(xxxx)” after calculations?
Usually “float(default=xxxx)” is used to convert a state or an attribute.
Same about “int(00)”.

Removing the Units has done it!!! I was thinking that might be it. Thanks for the tip regarding string vs numeric. I should have twigged it when the Template return was also showing the first few lines of code.

As for the code, it’s basically a copy-paste from this thread that I modified what I thought might suit my install best - Solar battery run time till empty - #39 by ziptbm