After reading about the reasons why a sensor’s .last_changed attribute does not persist between HA restarts… I have attempted to start storing last changed information on a handful of sensors in input_datetimes instead.
I have some template sensors that check the last_changed time on motion/door sensors, and they get thrown off after a restart because the last_changed gets reset.
However, I am basically having the same issue with the input_datetimes.
This is my automation. The trigger should be on every state change in the list of IDs, with a condition to stop “unknown”.
automation:
- alias: Store Last Changed
mode: parallel
trigger:
platform: state
entity_id:
- binary_sensor.door_front
- binary_sensor.door_back
- binary_sensor.door_garage
- binary_sensor.door_studio
condition:
condition: template
value_template: '{{ trigger.to_state.state != "unknown" }}'
action:
- service: input_datetime.set_datetime
data_template:
entity_id: >-
input_datetime.{{ trigger.entity_id.split('.')[1] }}_last_changed
time: '{{ (as_timestamp(now()) | timestamp_custom("%H:%M:%S", true)) }}'
date: '{{ (as_timestamp(now()) | timestamp_custom("%Y-%m-%d", true)) }}'
I have an input_datetime for each sensor with the same name + _last_changed:
input_datetime:
door_front_last_changed:
name: Last changed
has_date: true
has_time: true
Everything here works great. The proper input_datetime gets updated reliably each time it’s corresponding door opens.
However, if I reboot HA, I check the state of the input_datetime, and it’s back to “1970-01-01 00:00:00” until the sensor changes state again.
It is possible that this also only happening when HA is restarted “shortly” after the state change (within 10 minutes or so)
Some of the datetimes do survive the restart.
I also notice that on the binary_sensor, the “timestamp” attribute also reverts back to a previous timestamp.
Is there some kind of interval that HA backs up the states of the sensors for restoration after restart?
I would think that it would save the state during the restart command regardless of how long it’s been, but that seems to be the only thing I can think of that would cause what I am experiencing.
In the end, all I am seeking is a way to have persistent “last_changed” data for some of my sensors that survives a restart. I am baffled by how difficult it has been to accomplish such a seemingly simple task.
Anyone have any ideas here? I am open to experimentation, it’s just not going well so far and this method seems to be causing new issues. I don’t love how many extra sensors, templates, and automations I have to make, and how easily the data can drift.
Thanks!