State is X within time period

A number of automations I have depend on determining whether someone has been home within the last 12 hours. With kids forgetting to charge their phones and older kids away from the home for periods of time, it is useful to have this. I’ve been doing it with a condition like this:

      - condition: not
        conditions:
          - condition: state
            entity_id: person.name
            state: "not_home"
            for:
              hours: 10

The reason for doing it this way is that if I merely look at the state of the person being home at the time of the automation, it may not be accurate due to the phone losing power overnight.

However, I found this morning that if HA is restarted, an “unknown” can be inserted into this time period and throw a wrench in the way I do it.

Is there a preferred way to determine if an entity state has been something within a time period?

You can leverage a History Stats sensor to handle that:

sensor:
  - platform: history_stats
    name: Person A History 10hr
    entity_id: person.a
    state: "home"
    type: count
    start: "{{ now() - timedelta(hours=10) }}"
    end: "{{ now() }}"

You would then either use this directly in an automation as a condition:

trigger:
condition:
  - condition: numeric_state
    entity_id: sensor.person_a_history_10hr
    above: 0
action:

Or set up a template binary sensor to use as your condition:

template:
  - binary_sensor:
      - name: Person A Home last 10hr
        state: "{{ states('sensor.person_a_history_10hr')|int(0) > 0 }}" 

Perfect! Thank you.