Converting entity state to hours:minutes

Can somebody help me out with some templating? I want to create a sensor which shows how long ago our baby had its last feeding. I want to have that like “02:35”.

I have the following sensor which returns the time of last feeding
{{ state_attr(‘sensor.baby_last_feeding’,‘end’) }} returns: 2022-03-30T17:16:00+02:00

this should work:

{{ as_timestamp(state_attr('sensor.baby_last_feeding','end')) | timestamp_custom('%H:%M') }}

Thanks! That does work, but it gives me the time of the last feeding.

Maybe my initial post wasn’t clear, but I what I want is that if the last feeding for example was 18:00 and the time now is 20:15, the template should show: 2:15.

So hours:minutes ago since last feeding.

Than it should be:

{{ (as_timestamp(now()) - as_timestamp(state_attr('sensor.baby_last_feeding','end'))) | timestamp_custom('%H:%M') }}
1 Like

Exactly what I was looking for! Thank you!

I don’t know about you but if I don’t include false as the second argument in the timestamp_custom function, the calculated time difference isn’t offset correctly with respect to my timezone.

{{ (now().timestamp() - state_attr('sensor.baby_last_feeding','end') | as_timestamp) | timestamp_custom('%H:%M', false) }}

1 Like

You are right! The time was off by 1 hour for me. With the false included it’s corrected. Thanks!

I’ve not noticed that before but just did some testing:

So I guess it depends on the format of the datetime.

most of the time I use input_datetimes that likely convert it to local time in the timestamp. So it works without it.

but the uptime sensors state (which is like the OP’s) doesn’t convert to local time so it’s off and the ‘false’ is needed.