#calculated time remining

1 messages · Page 1 of 1 (latest)

finite pond
#

hello i have probleme with my action is dont write my value

target:
entity_id: input_number.pompe_next_trigger_in_minutes
data:
value: >
{% set times = ['06:00:00', '10:00:00', '17:00:00'] %}
{% set now = now() %}
{% set now_stamp = as_timestamp(now) %}
{% set next_time = 0 %}

{% for time in times %}
  {% set time_stamp = as_timestamp(strptime(time, '%H:%M:%S')) %}
  {% if time_stamp > now_stamp %}
    {% set next_time = time %}
    {% break %}
  {% endif %}
{% endfor %}

{% if next_time %}
  {% set next_time_stamp = as_timestamp(strptime(next_time, '%H:%M:%S')) %}
  {% set minutes = (next_time_stamp - now_stamp) / 60 %}
  {{ minutes | round(0) }}
{% else %}
  1440  # Si après 17h, mettre 1440 minutes (24h)
{% endif %}

action: input_number.set_value

terse igloo
#

There's a few issues with your template. One, you're being bitten by scoping rules in templates. Assignments inside of blocks get reset. In your case next_time gets assigned and then reset outside of the for loop. You can get around this by creating a namespace, like so:

{% set ns = namespace(next_time=0) %}

and then whenever you need to access the variable you do so like {% set ns.next_time = some_value %}

The other issue is that converting to a timestamp like you are is setting the date portion to some time in the distant past so your if condition is never true. You can look at using today_at("17:00") and doing your comparison with that. I'm not 100% sure what you want to do if next_time is set, but the following snippit of template code sets next_time

{% set times = ['06:00:00', '10:00:00', '17:00:00'] %} 
{% set now = now() %}
{% set now_stamp = as_timestamp(now) %} 
{% set ns = namespace(next_time = 0) %}

{% for time in times %}
  {% set time_stamp = today_at(time) %}
  {% if time_stamp > now %}

    {% set ns.next_time = time %}
    {% break %}
  {% endif %}
{% endfor %}

next_time is: {{ ns.next_time }}

you can dump this into the template editor available in the developer tools page

finite pond
#

a big thank you to you your explanations are very clear I still have a little trouble with YAML I come from C++ and assembler I will try again to practice good day and thank you again

grizzled bear
#

You could do all that without looping, which would also allow you to avoid scoping issues and dealing with namespace


{% set times = ['06:00:00', '10:00:00', '17:00:00'] %}
{% set next_list = times | map('today_at') | select('>', now()) | list %}
{{ 1440 if not next_list else ((next_list | min - now()).total_seconds() / 60) | round(0) }}
finite pond
#

how i can change 06:00:00 by input_datetime1 10:00:00 by input_datetime2 17:00:00 by input_datetime3 ?

grizzled bear
#
{% set entities = ['input_datetime.input_dt_1', 'input_datetime.input_dt_2', 'input_datetime.input_dt_3'] %}
{% set times = entities | map('states') | list %}