Need help with automation calculation

Hey all, I am creating an automation that announces when a meal needs to be started in order to be done by dinnertime. I am trying to do a calculation for the difference in time but can’t figure it out. Here’s an example:
I want to do states(calendar.meals.attributes.end_time - states(calendar.meals.attributes.start_time and announce it as a duration kind of. so if the end time is 6pm today and the start time is 2pm today then I want to announce that the meal takes 4hours. Is there a way to do the calculation within the automation?

If not, I was thinking about creating a sensor in the config yaml but I’m so bad with the formatting that I can’t get it right. Here is the action of my automation.

action:
  - service: notify.alexa_media
    data:
      message: >-
        Dinner for tonight is '{{ states.calendar.meals.attributes.message }}'
        and takes'{{ TIME IT TAKES TO COOK}}' hours
      data:
        type: tts
        value_template: ""
      target: media_player.theater_echo
mode: single

If for some reaon I can’t get it all done from within the automation itself, here is the code I was attempting in the templates.yaml (I found this chunk in the forumn and it seemed like it would work)

    - name: meals_cook_time
      state: >
          {% set x1 = as_timestamp(states(calendar.meals.attributes.end_time)) %}
          {% set x12 = as_timestamp(states(calendar.meals.attributes.start_time)) %}
          {{ x2, x1 }}
          {{ x2 - x1 }}
          {% set time = x2 - x1 | int(0) %}
          {{ time }}

and I was going to modfy this last mit to work inside of the automation

The sun rose {{ (time / 3600) | int }} hours {{ (((time / 3600) % 1) * 60) |int }}

Any help would be appreciated!

Check out easy time macro, calculations done for you.

{% from 'easy_time.jinja' import big_time_between %}
{{ big_time_between('calendar.meals', 'calendar.meals', 'start_time', 'end_time') }}

output e.g.

3 hours 5 minutes and 2 seconds

has a bunch of other macros too that make time easier to manage in HA templates.

Done, worked great. TYVM!

1 Like