History_stats configuration unexpected value

I have setup a history_stats sensor but the value its returning is making me think I may not understand the documentation on this correctly.

I setup my history_stat sensor based on the starts today at 6, lasts 5 hours.

sensor:
  - platform: history_stats
    name: Foo
    entity_id: binary_sensor.bar
    state: "on"
    start: "{{ now().replace(hour=17, minute=0, second=0) }}"
    duration:
      hours: 12

My understanding that this would apply starting at 5 PM for 12 hours.

I didn’t see any errors in the log and I have the information in the recorder (purge_keep_days is 28)

Where I am confused is that the where as checking the history for binary_sensor.bar I see it was on from 8:58 PM until 5:12 AM but the history_stat (sensor.foo) the value reaches 3.03 hours at 11:59 PM. I am guessing the issue might be related to the day change or maybe I don’t understand the history_stat sensor correctly.

Thanks!

Yes. What you have will only measure from 5pm to midnight. As soon as the date changes at midnight it will no longer be collecting data as it is before 17:00 on that day.

Instead of a start and duration you could try this:

    end: "{{ now().replace(hour=5, minute=0, second=0) }}"
    duration:
      hours: 12

So from 5AM back 12 hours. I think that will work.

FYI, you can use {{ today_at("05:00") }} for easier reading.

if what tom said doesn’t work, you can do this:

sensor:
  - platform: history_stats
    name: Foo
    entity_id: binary_sensor.bar
    state: "on"
    start: >
      {% set start = today_at('17:00') %}
      {% if start > now() %}
        {{ start - timedelta(days=1) }}
      {% else %}
        {{ start }}
      {% endif %}
    duration:
      hours: 12

This is doing my head in. :confused:

At and before 5pm the start time is 5PM today. Yet after 5pm the start time is 5pm yesterday. As it only records after 5PM why not just do:

    start: >
      {{ today_at('17:00')  - timedelta(days=1) }}

This will always start at 5pm yesterday.

Yah sure, that works too. Just change the 17 to 05

But that would be the end time?

I don’t get it. Will have a bit more of a think.

yah, brain fart

1 Like

Thanks! I will test this out and mark the solution. Really appreciate the explanation