Find out how long the sensor/switch was turned on in the last 24h

I have the following sensor which has following state info:

  - sensor.0x70b3d52b6000f48e_current
  - sensor.0x70b3d52b6000f48e_energy
  - sensor.0x70b3d52b6000f48e_energy_cost
  - sensor.0x70b3d52b6000f48e_indicator_mode
  - sensor.0x70b3d52b6000f48e_last_seen
  - sensor.0x70b3d52b6000f48e_power
  - sensor.0x70b3d52b6000f48e_power_outage_memory
  - sensor.0x70b3d52b6000f48e_voltage

What I want to find out - is how long in the last 1h/12h/24h/1w/etc the sensor was in ‘ON’ condition.

How do I do this?

There’s the

but you need an entity with an on/off state.
These sensors states are probably numbers.

This is what State tab shows of the sensor:

{
    "child_lock": "UNLOCK",
    "current": 0,
    "indicator_mode": "off/on",
    "last_seen": "2022-10-13T12:13:19-07:00",
    "linkquality": 51,
    "power": 0,
    "power_outage_memory": "restore",
    "state": "OFF",
    "voltage": 119,
    "device": {
        "applicationVersion": 160,
        "dateCode": "20210625",
        "friendlyName": "TuYa Smart Plug - Master Bedroom",
        "hardwareVersion": 3,
        "ieeeAddr": "0x70b3d52b6000f48e",
        "manufacturerID": 4660,
        "manufacturerName": "_TZ3000_okaz9tjs",
        "model": "TS011F_plug_3",
        "networkAddress": 55625,
        "powerSource": "Mains (single phase)",
        "softwareBuildID": "20B+TZSKT11BS105",
        "stackVersion": 1,
        "type": "Router",
        "zclVersion": 2
    },
    "energy": null,
    "update": {
        "state": null
    },
    "update_available": null
}

The state “OFF” should be the right one for this case, no?

Is there not a switch.0x70b3d52b6000f48e ?

Which integration is providing the entities ? Zigbee2MQTT ?

Integration is provided by zigbee2mqtt. There are both sensor.0x70b3d52b6000f48e and switch.0x70b3d52b6000f48e

I created two following entries in the configuration.yaml

   - platform: history_stats
     name: Master Bedroom Sensor ON today
     entity_id: sensor.0x70b3d52b6000f48e
     state: "ON"
     type: time
     start: "{{ now().replace(hour=0, minute=0, second=0) }}"
     end: "{{ now() }}"

   - platform: history_stats
     name: Master Bedroom Switch ON today
     entity_id: switch.0x70b3d52b6000f48e
     state: "ON"
     type: time
     start: "{{ now().replace(hour=0, minute=0, second=0) }}"
     end: "{{ now() }}"

But it both shows the time as 0, despite the fact that the switch is on.

How often the history_stats are updated? How do I know that the sensor I created actually works as expected?

Yes that looks right, might need to give it a while

Did you know you can rename the device in Z2M from 0x70b3d52b6000f48e to something more meaningful ?

I know, but then I need to go and update all dashboards and automations…

Ah right, ok