Time calculation hour addition

Hello all,

I’m new in Home Assistant and I really appreciate this tool.
I have searched for hours now in this blog but without succeeding.
I want to calculate an hour from one reference hours (12:00) substract or add a number of hour comming from an input_value. I want to use this calculation in automation as I have several conditions before.

An example of what I have tried :

  - service: input_datetime.set_datetime
    data:
      time: {{ as_timestamp(strptime('12:00:00' , '%H:%M:%S') - ((states.input_number.piscine_nombre_fonctionnement_heure.state * 3600|int) / 2)) | timestamp_local }}      
    target:
      entity_id: input_datetime.piscine_debut_periode

Then I have switched to development tool and test several things like:

{{ as_timestamp(strptime(states.input_datetime.piscine_heure_pivot.state , '%H:%M:%S')) - as_timestamp(strptime(states.input_number.piscine_nombre_fonctionnement_heure.state|int , '%H')) }}

but I have still error ‘Template error: strptime got invalid input ‘6’ when rendering template’.

All help is welcome :slight_smile:

Thank you in advance.

Have you looked into this?

  - service: input_datetime.set_datetime
    data:
      timestamp: >
        {{ (today_at('12:00:00') + timedelta(hours = states('input_number.piscine_nombre_fonctionnement_heure') | float(0))).timestamp() }}
    target:
      entity_id: input_datetime.piscine_debut_periode

If that fails to work (potentially because the template reports a timestamp value that includes the current date) then use this one:

  - service: input_datetime.set_datetime
    data:
      time: >
        {{ (today_at('12:00:00') + timedelta(hours = states('input_number.piscine_nombre_fonctionnement_heure') | float(0))).strftime('%H:%M:%S') }}
    target:
      entity_id: input_datetime.piscine_debut_periode

Thank you very much to both of you!
@Taras, your code is the solution! It works fine. Thank you!
@akappa, thank you for sharing, I’ll read it carrefully (didn’t find it despite a lot of search…)

1 Like

You’re welcome!

If you have chosen my suggestion to be the solution, please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions. Please note that only one post in the entire topic can have the Solution tag.

For more information about the Solution tag, refer to guideline 21 in the FAQ.