History_stats time type - What is the Time?

I read through a few related items like this, but didn’t see much in terms of a resolution and perhaps I’m just not clear on how a time type history_stats works. I have a Ubitquity doorbell that has a binary sensor for person detected:

I added the following sensor:

  - platform: history_stats
    unique_id: doorbell_last_person
    name: Doorbell - Last Person
    entity_id: binary_sensor.front_door_person_detected
    state: "on"
    type: time
    start: "{{ now().timestamp() - 86400 }}"
    end: "{{ now() }}"

I expect this sensor to tell me that the last motion was at 2:34:09. When I look at the entity state, I see this:

I’m not sure what the 0.067 number represents, but it isn’t that many hours ago. I looked into the .last_changed value, but that seems to be only when I restarted HA:

{{ relative_time(states.sensor.doorbell_last_person.last_changed) }} ago

image

How should I be translating the state of a time history_stats item? Thanks!

image

So for your example it is the number of hours over the past 24 that the door was open.

And tracked time, meaning *duration of * time in the referred to state: on ?

So I guess that’s not what I want…

What is the goal?

I want to be able to mimic the integration’s view where it says “1 hour ago”, indicating the a person was last seen 1 hour ago.

When I tried to pull the .last_updated of the Unifi Protect integration’s binary_sensor, it seemed off (perhaps it was the time i restarted HA, so I thought “oh, the history_stats would work over restarts better.”

Do you need it to directly state the relative time, or should it return a timestamp?

A timestamp would work, then I can display it differently in different spots. I changed how I was searching and found this post:

I think that is basically what I want, so I need to define a trigger to capture when the state on the binary_sensor goes from off to on, and populate another sensor with the timestamp?

Yep, that’s the way I would do it.

template:
  - trigger:
      - platform: state
        entity_id: binary_sensor.front_door_person_detected
        to: 'on'
    sensor:
      name: Front Door Person Detected Timestamp
      device_class: timestamp
      state: "{{ now() }}"

Just FYI, this should be placed in your configuration.yaml file or a properly included file for template entities.

1 Like

Perfect! Thanks for the quick help!