Track hours not home?

I’m wondering why my code is not working. I did it like that for the state because I got other zones as well like work and I just want to know how long I was not at home.

- platform: history_stats
  name: Sascha - Zeit in Abwesenheit
  entity_id: person.cptdaydreamer
  state: "{{ 'home' not in states('person.cptdaydreamer') }}"
  type: time
  start: "{{ now().replace(hour=0, minute=0, second=0, microsecond=0) }}"
  end: "{{ now() }}"

For presence it works well:

- platform: history_stats
  name: Sascha - Zeit zu Hause
  entity_id: person.cptdaydreamer
  state: "home"
  type: time
  start: "{{ now().replace(hour=0, minute=0, second=0, microsecond=0) }}"
  end: "{{ now() }}"

state does not allow templates. Just make a second sensor that tracks 24 hours - home.

What? I already got this kind of sensor as you can see. I want the opposite and the problem is that I have multiple zones so I cannot say state: not_home

Right, but there’s 24 hours in a day and you now want the opposite number. So, 24 hours - (hours at home) = hours away.

Make a template sensor that does this subtraction.

You could even make it smart, by looking at the current time of the day and subtracting from that.

e.g.

{% set total = (now() - today_at("00:00")).total_seconds() %}
{{ total - states('sensor.time_home') | float }}

assuming that time_home is in seconds

1 Like

What Petro says is that you cannot use a template in the state: (even if you could, your template is just returning a boolean, anyway).

image

You could use a list, though, so you could just enumerate the zones which are not “home”, although it’s not great for maintainability, so just use Petro’s idea.

Sorry, I’m too dumb. I’m not able to configure it. How do you mean it? A sensor with your code and than a history_stats entity with this sensor?

Keep your “Time at home” history stats sensor. Then create a template sensor using the template I provided above, just make sure you update the entity_id in the template to use your “time at home” sensor.

Keep in mind that history stats and template sensors are separate integrations, so they will not go in the same spot in your configuration.yaml.

You mean like this:

- platform: template
  sensors:
    sascha_zeit_nicht_zu_hause:
      value_template: >
        {% set total = (now() - today_at("00:00")).total_seconds() %}
        {{ total - states('sensor.sascha_zeit_zu_hause') | float }}

Looks wrong tbh:

sensor.sascha_zeit_zu_hause is the history stats sensor from above.

I would assume so. I don’t know what units your sensor is in. If you want the values to be numerical, add device_class: duration and unit_of_measurement: s.

Still not able to get what I want because I want it like this:
image
But instead of 0,0 hours, I want the value. Damn programming in Java and Python is easy. This here is really tricky.