Adding x-minutes to an alarm datetime dynamically

Hi!

I have an input_datetime helper for my wake up alarm. Currently I have a hard coded value for the number of seconds to add to the datetime to serve as a grace period for some of my automations. This works well, but I would like the number of added seconds to be dynamic based on the value of an helper instead of being static. I would also like it to be in minutes instead of seconds.

This is the working code I have today (static value 7200):

service: input_datetime.set_datetime
   data:
  time: >-
    {{(((state_attr('input_datetime.alarm' , 'timestamp')) + 7200) |
    timestamp_custom('%H:%M', false))}}
target:
  entity_id: input_datetime.alarmtillegg

I’ve replaced the static number with an new input_number.alarmtilleggstid helper in the template like so:

{{(((state_attr('input_datetime.alarm' , 'timestamp')) + (states('input_number.alarmtilleggstid'))  |
    timestamp_custom('%H:%M', false )))}}

But the template fails:

ValueError: Template error: timestamp_custom got invalid input '6000.0' when rendering template '{{(((state_attr('input_datetime.alarm' , 'timestamp')) + (states('input_number.alarmtilleggstid')) | timestamp_custom('%H:%M', false )))}}' but no default was specified

Would greatly appreciate any help to get futher with this!

States are always strings, you need to apply the int or float filter to the state of the Input number.

However, I would suggest avoiding timestamps and just using datetime objects and methods, but the exact way to set that up depends on whether input_datetime.alarm is time-only or date and time:

Date and Time:
{% set current = states('input_datetime.alarm) | as_datetime | as_local%}
{%- set add_min = states('input_number.alarmtilleggstid') | int %}
{{- (current + timedelta(minutes = add_min)).strftime('%H:%M') }}

Time Only:
{% set current = today_at(states('input_datetime.alarm')) %}
{%- set add_min = states('input_number.alarmtilleggstid') | int %}
{{- (current + timedelta(minutes = add_min)).strftime('%H:%M') }}
1 Like

Mine is time only. Worked like a charm! Thank you very much!

1 Like