Create a trigger based on variable time delta

I want to create a trigger for my heating system to start so it ends at a fixed time based on a given end time minus yesterday’s duration.
I get the notification Failed to load integration for translation: Integration ‘trigger’ not found.

sensor:
  - platform: history_stats
    name: Heater On Time Yesterday
    entity_id: switch.sonoff_10022b319d_1
    state: "on"
    type: time
    start: "{{ now().replace(hour=0, minute=0, second=0) - timedelta(days=1) }}"
    end: "{{ now().replace(hour=23, minute=59, second=59) - timedelta(days=1) }}"
   Template sensors
template:
  - sensor:
      - name: "Heater end Time"
        state: "{{ today_at(states('input_datetime.sk_warm_end_time')) }}"
      - name: "Heater end Time Hours "
        state: >
                {{ states('sensor.heater_end_time') | as_timestamp | timestamp_custom('%H') }}
      - name: "Heater end Time min"
        state: >
                {{ states('sensor.heater_end_time') | as_timestamp | timestamp_custom('%M') }}
      - name: "Heater duration in min"
        state: >
         {{ (states('sensor.heater_on_time_yesterday') | float * 60) | round(0) }}

      - name: "Heater end time hours in min"
        state: >
               {{ (states('sensor.heater_end_time_hours') | float * 60) | round(0) }}
      - name: "Heater start in min"
        state: >
                {% set T1 = states('sensor.heater_end_time_hours_in_min')|float %}
                {% set T2 = states('sensor.heater_end_time_min')|float %}
                {% set T3 = states('sensor.heater_duration_in_min')|float %}
                {{ ((T1 + T2 - T3) ) | round(0,) }}
      - name: "Heater start in hours min"
        state: >
                {{ (states('sensor.heater_start_in_min') | int * 60) | timestamp_custom('%H:%M', false) }}

# I now have the number of minutes from midnight to add to today's date @ 00:00:00 hours to calculate the start time so it finished at the desired time 
               
trigger:
    - platform: state
    - sensor:
      - name: Heater CV klep start
      unique_id: Heater_start
      device_class: timestamp
      state: >-
               {{ states('input_datetime.heater_start_time') | today_at + timedelta(minutes= Heater start in min) | int(0))

That part is completely bogus

image

I can see the answers in this card. I need help to get the switch.sonoff_10022b319d_1 to start at 1230 min after midnight or 20:30

I have ben searching for code but have not been succesful

Try to read and understand the doc:

If something is unclear, please come back with specific questions

I tried this code but does not work

 - service: input_datetime.sk_heater_on
    data: {} 
timestamp: >-
 {{ as_timestamp(now() + timedelta(minutes = 
        states('sensor.heater_start_in_min')| int)) | int }}

the state of input_datetime.sk_heater_on is 00:00:00
the state of sensor.heater_start_in_min is 1230

desired outcome
the state of input_datetime.sk_heater_on is 20:30:00

Where is this stuff coming from, because none of it makes sense…?

There is no action input_datetime.sk_heater_on. All the core actions available for input_datetime entities can be found in Input Datetime - Actions.

Declaring an empty dictionary after data ( data: {} ) is saying “There is nothing in data”… but you do have something that should be in data… the timestamp.

I think what you are going for with this action is:

- service: input_datetime.set_datetime
  target:
    entity_id: input_datetime.sk_heater_on
  data: 
    timestamp: >-
      {% set offset = states('sensor.heater_start_in_min')| int(0) %}
      {{ as_timestamp(now() + timedelta(minutes = offset)) }}

Probably some AI that guesses and doesn’t care too much about indents either.

1 Like

Hi I copied the code into config. Any suggestions?

several notifications

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2117, in forgiving_as_timestamp
    return dt_util.as_timestamp(value)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/util/dt.py", line 153, in as_timestamp
    raise ValueError("not a valid date/time.")
ValueError: not a valid date/time.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 633, in async_render
    render_result = _render_with_context(self.template, compiled, **kwargs)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2735, in _render_with_context
    return template.render(**kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/jinja2/environment.py", line 1304, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.12/site-packages/jinja2/environment.py", line 939, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 1, in top-level template code
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2120, in forgiving_as_timestamp
    raise_no_default("as_timestamp", value)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1911, in raise_no_default
    raise ValueError(
ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ states('sensor.heater_end_time') | as_timestamp | timestamp_custom('%H') }}' but no default was specified

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 750, in async_render_to_info
    render_info._result = self.async_render(  # noqa: SLF001
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 635, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ states('sensor.heater_end_time') | as_timestamp | timestamp_custom('%H') }}' but no default was specified
2024-12-03 20:06:07.687 ERROR (MainThread) [homeassistant.components.template.template_entity] TemplateError('ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ states('sensor.heater_end_time') | as_timestamp | timestamp_custom('%H') }}' but no default was specified') while processing template 'Template<template=({{ states('sensor.heater_end_time') | as_timestamp | timestamp_custom('%H') }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.heater_end_time_hours'
2024-12-03 20:06:07.688 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template<template=({{ states('sensor.heater_end_time') | as_timestamp | timestamp_custom('%M') }}) renders=2>
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2117, in forgiving_as_timestamp
    return dt_util.as_timestamp(value)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/util/dt.py", line 153, in as_timestamp
    raise ValueError("not a valid date/time.")
ValueError: not a valid date/time.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 633, in async_render
    render_result = _render_with_context(self.template, compiled, **kwargs)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2735, in _render_with_context
    return template.render(**kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/jinja2/environment.py", line 1304, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.12/site-packages/jinja2/environment.py", line 939, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 1, in top-level template code
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2120, in forgiving_as_timestamp
    raise_no_default("as_timestamp", value)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1911, in raise_no_default
    raise ValueError(
ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ states('sensor.heater_end_time') | as_timestamp | timestamp_custom('%M') }}' but no default was specified

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 750, in async_render_to_info
    render_info._result = self.async_render(  # noqa: SLF001
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 635, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ states('sensor.heater_end_time') | as_timestamp | timestamp_custom('%M') }}' but no default was specified
2024-12-03 20:06:07.689 ERROR (MainThread) [homeassistant.components.template.template_entity] TemplateError('ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ states('sensor.heater_end_time') | as_timestamp | timestamp_custom('%M') }}' but no default was specified') while processing template 'Template<template=({{ states('sensor.heater_end_time') | as_timestamp | timestamp_custom('%M') }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.heater_end_time_min'
2024-12-03 20:06:07.691 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template<template=({{ (states('sensor.heater_end_time_hours') | float * 60) | round(0) }}) renders=2>
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2354, in forgiving_float_filter
    return float(value)
           ^^^^^^^^^^^^
ValueError: could not convert string to float: 'unavailable'

What do you mean by that? What I posted above is just a correction to the Action you posted earlier. You cannot just paste it anywhere. AFAIK, there are only 3 use allowed cases for an action that contains templating… You need to post the full, current, properly-formatted configuration for the script/automation, trigger-based template sensor, or non-sensor template entity you are using it in.

Hi

That is probably beyond my capabilities. I suppose I need to accept that what I want is just too difficult

Why not just trigger your automation using a Numeric State trigger for the state of sensor.heater_start_in_min going below 1?

Hi

In my house, I have 4 heating zones each with a thermostat and a valve. Each zone has potentially 2 scheduled warm up time and each has a different pre-heating time depending on the room and the weather conditions. Potentially there are 8 combinations of settings .

CV card

For now, my solution is to have several cards like in the image and manually enter the heater start time into the heater on-time input. This triggers the valve to open and the heater to be switched on at the required time.
I am retired and I can only manage simple code like, in Vbasic. HA is too complicated for me. I need the complete code that sets the input_datetime.sk_heater_on to the required time like I can do manually The rest of the automation is in place and works. I am just missing this step. I have spent hours researching HA but can’t figure out how to do this

after much study, integating suggestion and help from chatGPT this is a working code

alias: heater pre time
description: ""
triggers:
  - entity_id:
      - sensor.heater_on_time_yesterday
    trigger: state
conditions: []
actions:
  - target:
      entity_id: input_datetime.sk_heater_on
    data:
      time: >-
        {% set offset = states('sensor.heater_start_in_min') | int(0) %} {{
        (now().replace(hour=0, minute=0, second=0) +
        timedelta(minutes=offset)).strftime('%H:%M:%S') }}
    action: input_datetime.set_datetime
mode: single