Time Calculation

I have a time stored in a sensor as as string, for example 13:52:13. How can I take the current time and subtract the string to get the difference in hours and minutes, i.e 1:14, also as a string ? It seems like it would be a simple thing to do but I’ve tried many things without success.

My sensor is named “sensor.start_time”

Thanks.

Is sensor.start_time always a time that is today? If so, you could do

{% set seconds = now() | as_timestamp - today_at(states('sensor.start_time')) | as_timestamp %}
{% set hours = (seconds / 3600) | int %}
{% set minutes = (seconds / 60 % 60) | int %}
{{ hours }}:{{ '%02d' % minutes }}

If it is sometimes yesterday (but less than 24 hours ago), then you’ll have to check for the case where now minus the sensor’s time is negative, and adjust the math accordingly.

If it is sometimes yesterday, but might be more than 24 hours ago, then you don’t have enough information to calculate it correctly.

Edit: deleted the extraneous line in the template.

1 Like

Maybe something like this in a helper template:

{{ relative_time( now() - as_timedelta(states('sensor.start_time')) ) }}

You can look at Templating - Home Assistant to get more ideas.

[Edited for correctness]

2 Likes

Thanks for your help. This did the trick.