Hello all. Is there a way to switch the statement below to the “preferred method”. Also, how do I know when I would be better off to switch to the preferred method? Will the logs help me know when variables are not ready (at start up etc.)
<p>
The washing machine completed its cycle
{% set seconds = now().timestamp() - as_timestamp(states.sensor.washer_status.last_changed) %}
{% set hours = seconds / 60 %}
{% if (seconds / ( 60 * 60 )) | int == 1 %}
over an hour ago.
That’s assuming that’s an attribute of that sensor. I haver some that have that as an attribute. If you’re going after the inbuilt ‘last_changed’ then no, you still use states.xxx.xx.last_changed.
FWIW, you can take advantage of newly added functions like as_timedelta() to avoid having to set up all the timestamp math… and make the template a bit more readable.
{% set diff = now() - states.sensor.washer_status.last_changed %}
{% if diff.days > 0 %}
more than a day ago
{% elif diff >= as_timedelta("1:00:00") %}
more than an hour ago
{% elif diff >= as_timedelta("0:10:00")%}
more than ten minutes ago
{% endif %}