History sensor attribute seems wrong

I use history sensors to count how long a switch is on.

  - platform: history_stats
    name: irrigation_zone7_total_time_today
    entity_id: sensor.irrigation_sensor_zone7_switch
    state: 'on'
    type: time
    start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
    end: '{{ now() }}'

Firstly the actual state is (in my opinion) wrong.

My switch was on for 10 minutes today (controlled by an HA timer) which gives a state of 0.1666. Clearly this is a rounding issue (so you could, and probably will argue it is not wrong :wink: ) but would it have hurt for the history sensor to have saved a few extra decimals given it measure fractions of a fairly large unit i.e. an hour?

Even so…

how does 0.17 hours translate to the attribute value: 9m?


I see that, “The History Stats integration was introduced in Home Assistant 0.39” so either I am wrong or no one has noticed this in a long time.

But I also see that, “it’s used by [only] 3.7% of the active installations.” So I’m probably banging my head against a wall on this one :slight_smile:

The state is the time in hours. 0.17 * 3600 = 612s, which is 10m12s. Each increment in the second decimal place represents an increase of 36s — an additional decimal would be 3.6s resolution, which is probably where it gets more precise than it is accurate.

It would be easy to “fix” this: see line 162 of this file:

but I’d argue that if you’re seeking that level of precision, you’re using the wrong tool. Note that the rounding is only in returning the internal value as the state, and “full” precision is retained internally.

And I’d probably support that argument. Except that I use it for informational purposes so it doesn’t makes my UI look very good!

It’s not really a big deal, just irritating…

And I still don’t understand where the value: 9m comes from?

(To edit the core would mean having to remember to keep it in sync with updates (at least) every month.)

See line 182, then line 330 of that file. The pretty_duration() function is turning the internal float hours value into a “pretty” integer number of minutes — must be fractionally under 10 mins. 0.165h (the minimum to show 0.17) is 9m54s.

Unless you submit it as a pull request for the core… :wink:

I think this is a flaw in history_stats. It should output seconds, which is the base units for all time conversions. Seems like an oversite.

I’d write a feature request to have units for the time.

Done, but I am not confident it will get any traction.

I would but Python is not my language…
I wish it was. There are plenty of pull requests I’d have considered if it were :wink: