Subtract two date.times to determine duration

Hi,

I have an entity that gives me a next_start_time and next_finish_time attributes. I want to subtract the two date.time from each other to be able to calculate the duration between the start and finish time (in minutes) by using YAML.

I want to use this duration to create an action. Let’s say, if the calculated duration less than 120 minutes, then I want to create an action. Also, let’s say the duration is more than 120 minutes, then I want to create a different action.

I have looked at the documentation, but have not yet find a workable solution in YAML.

Thanks in advance.

Hi, welcome to the forum!

Have a look at this: Templating - Time
And this: Search results for 'subtract time' - Home Assistant Community

Hi Nick,

thank you very much! I am very new to HA, although I have a background in industrial automation.

I will have a look at the provided link and hopefully I can get some info.

I got this one figured out. I created a new sensor and the calculation works as expected:

- platform: template

  sensors:

    next_loadshedding_duration:

      friendly_name: "Next Loadshedding Duration"

      value_template: "{{ (as_timestamp (state_attr( 'sensor.load_shedding_area_eskme_13_velddriftbergrivierwesterncape' , 'next_end_time')) - as_timestamp (state_attr( 'sensor.load_shedding_area_eskme_13_velddriftbergrivierwesterncape','next_start_time')) ) / 3600 | round (0) }}"

Is there a reason why you chose to create a Template Sensor using the 'legacy’ configuration format instead of ‘modern’ format?

BTW, if you want, you can write the template like this:

value_template: >
  {% set s = 'sensor.load_shedding_area_eskme_13_velddriftbergrivierwesterncape' %}
  {{ ((state_attr(s, 'next_end_time') - state_attr(s,'next_start_time')).total_seconds() / 3600) | round(0) }}

Please note that you must group the division with parentheses in order for round to act on the result of the division. If you don’t group it, the round filter will act on the value 3600 only (which achieves nothing because it’s already an integer value). Therefore the final result will not be a rounded integer value but a floating point number.

Hi,

thanks for pointing that out. It is valuable information indeed! I will see to it that I group the division, in order to get the desired result.

I am still new to HA, so I guess the legacy format was the 1st thing that came up. I will definitely explore the modern approach as I learn more.

Thanks again!

That’s interesting because the legacy format is described after the modern format in the documentation and indicates the legacy format is ‘no longer recommended’.