Convert `trigger.for` into a relative age

I’d like to receive a notification if my server load has been “unusually” high for a period, but include the duration in the message as a relative age. The snippet below works, but the time given by trigger.for is a timedelta object and it prints as “00:05:00”. Instead, I’d like it to show “5 minutes”. The relative_time function only works with datetime objects. Now, it’s not the end of the world if there is a tiny bit of duplication, but I’m also curious if this is possible.

One option is to write a long if-else statement for the different time ranges (e.g. if the delta time in seconds is between 0 and 60, then…), but this would seem to not be worth the effort and the configuration won’t be as readable as a more succint version.

- alias: "Notify If Server Load High"
  trigger:
    platform: numeric_state
    entity_id: sensor.load_15m
    above: 1
    for: 
      minutes: 5
  action:
    - service: notify.mobile_app_xxx
      data_template:
        title: "System"
        message: "The server load has been {{ states('sensor.load_15m') }} for {{ trigger.for }}."

PS: I know HA isn’t as such a system monitoring tool and that there are other solutions, but I think it’s justified since this monitors the HA server itself. Plus, I’m not aware of such tools doing push notifications.

TimeDelta can report in days, seconds, or microseconds. For your purposes, you can use seconds and convert it to minutes.

        message: "The server load has been {{ states('sensor.load_15m') }} for {{ trigger.for.seconds / 60 }} minutes."

This is a great answer, thanks. It strikes a good balance between complexity and duplication.

1 Like

This doesn’t work anymore, right? trigger.for.seconds now returns nothing for me. I don’t see a trigger.for.seconds in the automation variables in the trace viewer either. There’s only a trigger.for.total_seconds.

Home Assistant’s documentation indicates trigger.for contains a timedelta object.

Python’s documentation for a timedelta object indicates it has three attributes:

  1. days
  2. seconds
  3. microseconds

and one method:

  1. total_seconds()

Thank you for that. My bad, I meant to say that trigger.for.minutes wasn’t working. I’d seen that used in this post but it doesn’t actually work. But .seconds should work according to your info, so I’ll use that instead. Thanks

i am trying to use trigger.for.seconds and it always return null. any trick that i am missing?

- trigger:
      - platform: state
        entity_id: binary_sensor.door1
        from: 'on'
        to: 'off'
    sensor:
      - name: door last opened2
        state: "{{ trigger.for.seconds | int }}"

Because your State Trigger lacks a for option.