Inconsistent History Sensors - (possibly) since v0.113

I have some history sensors which measure how long a switch was on. Recently they have been giving inconsistent values.

All sensors are configured like this:

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

However the state and attributes are inconsistent.

They both have a state of 0.08 which is 4.8 minutes so why does one of them have 4m as its value attribute and one has 5m?

As I said I only noticed this happening recently, almost certainly since v113.


Incidentally, I believe they should both show exactly 5 minutes (or very close allowing for generous HA processing time) as it should be given they are on for the duration of a 5 minute delay. But I’ll cross that bridge later.

Did one of them start slightly before midnight?

No, they started at about 19:15

Looking at the source there’s a whole bunch of truncating (floor, and int) and just plain ignoring seconds altogether. It’s never going to be more accurate than +/- 1 minute.

e.g. seconds are discarded rather than rounding to the nearest minute in the output formatting:

    def pretty_duration(hours):
        """Format a duration in days, hours, minutes, seconds."""
        seconds = int(3600 * hours)
        days, seconds = divmod(seconds, 86400)
        hours, seconds = divmod(seconds, 3600)
        minutes, seconds = divmod(seconds, 60)
        if days > 0:
            return "%dd %dh %dm" % (days, hours, minutes)
        if hours > 0:
            return "%dh %dm" % (hours, minutes)
        return "%dm" % minutes

Looking at the above, 0.08hrs should actually output 4 minutes. Not sure how you got 5.

1 Like

Thanks!
Well I guess I’ll have to live with it.

I guessed it might be a rounding error somewhere but it doesn’t make much sense to me to have a history sensor that can be so inaccurate. It would be nice if the sensor just reported seconds and left it up to us to format how we liked.

But hey, ho.

Thanks again for looking at it.