By piecing together the posts of a few others, I have successfully created a display to show me how long my home is unoccupied by using a combination of a counter and a timer that indexes the counter every minute. So, from that the counter value is the number of minutes my home is unoccupied. I can show that counter value and recognize that it’s minutes but I’ve tried to show it in hours and days for times when it is unoccupied and that’s where I’ve stumbled. I’m using the timestamp_custom format below but there are 2 issues:
By default, it sees the counter value as seconds and not minutes. Even if I leave out the %S, it still sees it as seconds. I can have the timer index every second but that is not needed. Can I have timestamp_custom directly recognize that this value is in minutes without multiplying it or indexing the counter ever second?
When I include %d, I immediately get 1 day showing even if the unoccupied time is only a few minutes. How can I roll the “Days” over only after I have truly crossed over 23:59 hours?
Below is what I’m currently using:
{{ states('counter.home_unoccupied') | int ) | timestamp_custom('%d:%H:%M:%S', true) }}
You really don’t need all that. HA has entities specific for this kind of thing. You can create a last occupied sensor, and then a duration sensor. The rest will be handled by HA. No counters, no automations, just template sensors.
template:
- trigger:
- id: left
platform: state
entity_id: zone.home
to: "0"
- id: arrived
platform: state
entity_id: zone.home
not_to: "0"
sensor:
- name: Last Occupied
unique_id: last_occupied
device_class: timestamp
state: >
{{ now() }}
availability: >
{{ trigger.id == 'left' }}
- sensor:
- name: Unoccupied Time
unique_id: unoccupied_time
device_class: duration
unit_of_measurement: s
state: >
{{ (now() - states('sensor.last_occupied') | as_datetime).total_seconds() | int }}
availability: >
{{ 'sensor.last_occupied' | has_value }}
In the UI the last_occupied will be a relative time, e.g. 15 Minutes Ago
In the UI the Unoccupied time will be d HH:MM:SS, e.g. 00:15:00 for 15 minutes. or 1 day, 00:15:00 for 1 day and 15 minutes.
Did someone come or go? Trigger-based template sensors will be unknown when created until the first time it was triggered. After that, it will always have the last state, even after a restart.
I did have an unoccupied state happen and still got that. I have not been using a templates.yaml file and tried this code within the configuration.yaml file and also added a templates.yaml file and referenced it in the configuration.yaml file and get the same either way.
I tried several home/away cycles today but this is not triggering for some reason. My other away/home automatons are working and the attached trend shows I’m getting transitions to: 0 and not_to 0. Any reason why this template would not trigger and show the time away?