Calculate number of minutest since lastchanged

I am trying to calculate the number of minutes since the state of a switch has been changed. First of all, I calulate the delta like this

{% set delta= (now()-states.switch.lights_kitchen.last_changed) %}

That seems to give me a datetime with the difference. But now I like to know hoe many minutes this is. So I tried this:

{{ delta.strftime("%M")| int(0) }}

That gives me an error saying ‘datetime.timedelta object’ has no attribute ‘strftime’. So it seems that the resulting opbject is not a datetime but a timedelta object. I can’t find how to deal with that.

Any ideas?

Try this:

{{ (as_timestamp(delta)|int(0)/60)|round(0) }}

Tried that, but that results in:

ValueError: Template error: as_timestamp got invalid input '2:39:10.560590' when rendering template 'switch.kitchen_table_lamp Last changed: {{ states.group.lights_kitchen.last_changed }} Now: {{now()}} {{ now()-states.group.lights_kitchen.last_changed }}

Here is my full example code:

{% set delta= (now()-states.group.lights_kitchen.last_changed) %}
{{ (as_timestamp(delta)|int(0)/60)|round(0) }} 

Another approach:

{% set diff = as_timestamp( now() ) - as_timestamp( states.group.lights_kitchen.last_changed, now().timestamp() ) %}
{% set min = ( diff / 60 )|round(0, default=0) %}
{{ min }}

1 Like