I have this template to calculate the remaining time on a timer:
{% set f = state_attr('timer.living_room_movie_mode_timer', 'finishes_at') %}
{{ '00:00:00' if f == None else
(as_datetime(f) - now()).total_seconds() | timestamp_custom('%H:%M:%S', false) }}
What I want is to calculate how much time has passed on the timer. I understand there is a ‘duration’ attribute. I want to subtract the remaining time from the duration, but I’m just not savvy enough to get this to work.
Edit: Keep reading this solution does not work as intended.
Okay, I did figure it out:
{% set d = state_attr('timer.living_room_movie_mode_timer','duration') | as_timedelta %}
{% set f = state_attr('timer.living_room_movie_mode_timer', 'finishes_at') | as_datetime %}
{{ '00:00:00' if f == None else
(( d.total_seconds() - ( f - now()).total_seconds())) | timestamp_custom('%H:%M:%S', false) }}
If the timer is not active it will have no finishes_at attribute therefore the state_attr() function will report None. However the as_datetime filter doesn’t accept the value None so it will result in an error that aborts further processing of the template.
The linked example handles the situation correctly.
There does seem to be a problem with my solution that has something to do with the placement of the ’
| as_datetime
when setting the f variable.
When the timer resets or finishes, I get this error
TypeError: float() argument must be a string or a real number, not 'NoneType'
If I set the f | as_datetime in the template itself instead of when defining it in the variable, the ‘if f == None’ is correctly checked, but then the template does not work
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'
I’m not even sure if I’m explaining this well, but I figure someone who understands this better may be able to figure out the issue.