Time calculations

This code is very old. I’ve updated it in another post.

for calendar entities…

          {%- set word_for_and = 'and' %}
          {%- set up_time = (states('calendar.xyz', 'end_time') | as_datetime | as_local - now()).total_seconds() %}

          {%- macro phrase(name, plural_name, divisor, mod=None) %}
            {%- set value = ((up_time // divisor) % (mod if mod else divisor)) | int %}
            {%- set name = plural_name if value > 1 else name %}
            {{- '{} {}'.format(value, name) if value | int > 0 else '' }}
          {%- endmacro %}
          
          {%- set values = [ 
                     phrase('week', 'weeks', 60*60*24*7), 
                     phrase('day', 'days', 60*60*24, 7),
                     phrase('hour', 'hours', 60*60, 24),
                     phrase('minute', 'minutes', 60), 
                     phrase('second', 'seconds', 1, 60) 
                 ] | select('!=','') | list %}
                        
          {{ values[:-1] | join(', ') ~ ' ' ~ word_for_and ~ ' ' ~ values[-1] if values | length > 1 else values | first  | default }}
1 Like

Sweet! I’m sure this will come in handy in the future. I’m using your last version to tell me how long I’ve been in bed when I get up in the morning rather than uptime and I plan to set something similar up to report how long I’ve been absent from home when I go away for days or weeks at a time.
Aside from being more streamlined, are there any advantages of using your new method? I already have your previous work doing a great job with that first task so I’m wondering if I should bother replacing that older code in what I’ve done so far.
Thanks again!

I was looking how to do this and found this old thread and after a lot of troubleshooting, I figured out that you can simply use the relative_time function.

Example:

{{ relative_time(states.vacuum.litter_robot_litter_box.last_changed)}}

Gives:

3 minutes

Which is exactly what I was looking for my notifications!

Just keep in mind that relative_time does not work with dates that are in the future. That’s why we have to create the large template for future events.

You can also get around this by subtracting the time difference from the current time, e.g.:

{{ relative_time(now() + (now() - strptime(states('sensor.washer_dryer_remaining_program_time'), "%Y-%m-%dT%H:%M:%S%z"))) }}

This post is outdated, relative_time now updates once a minute on the minute. I added this to HA core last year sometime.

EDIT: Also made a custom library to handle future dates.