I assume that I am overseeing something but I simple cannot get my head around how to accomplish this: I want that show the difference between now() and last_changed of a sensor only in minutes.
The result of that template should be the number of seconds since the sensor last changed. Try it in the template editor: here’s mine with a sensor on my system:
now: {{now()}}
as timestamp: {{as_timestamp(now())}}
last ch.: {{ states.binary_sensor.zugaengeeg.last_changed }}
last ch. as timestamp:{{ (as_timestamp(states.binary_sensor.zugaengeeg.last_changed)) }}
difference: {{ (as_timestamp(now()) - as_timestamp(states.binary_sensor.zugaengeeg.last_changed)) | timestamp_custom ('%H:%M:%S') }}
diff as timestamp: {{ (as_timestamp(now()) - as_timestamp(states.binary_sensor.zugaengeeg.last_changed))}}
diff in minutes: {{ (as_timestamp(now()) - as_timestamp(states.binary_sensor.zugaengeeg.last_changed)) / 60 | int}}
From what I see, last changed of my device was app. 2h and 8 minutes ago, but the difference is calculated a hour less. Is this due to time zones? how do I compensate this?
It was actually 8 minutes 40 seconds ago once you allow for the timezones: 12:12:20 UTC versus 14:21:00 UTC+2. The calculation is correct.
The only issue there is your timestamp_custom, which should include local=False after the format as you’re using it for an absolute time difference (docs). That would then read 00:08:40.
Single states show correct times but the difference seams to ignore what ever seeting and removes 2 hours from the result.
I have no clue what I am doing wrong.
@Troon: It seems time zones are messing up the result. Did I set up something wrong? Why is UTC only considered in the calculation but not in the date object of now() itself?
Nothing is being messed up. now() is reporting time in your local timezone of UTC+2, and the sensor last_changed is reporting in UTC.
Because both of these times are “timezone-aware” — that is, they refer to their timezone — you can do calculations with them. From that screenshot, the difference is indeed about 23 minutes from 13:28 UTC to 15:51 UTC+2.
It’s all working fine as far as I can see. Have a look at the history chart for your binary sensor: how long ago does that say it last changed?
I’m hoping to retrieve the amount of hours and minutes from ‘now’ to time of the next alarm to use them in the same TTS message, it shows the hours in this card but I can’t see where i can find the value to attempt to extract it.
I’ve spent hours looking at it but really don’t know how I should be doing this. Please could you help?