Jinja2: string to time, then timedelta?

Hi everybody,

I am trying to get the earliest time value from multiple sensors, then calculate a time value from it.

{% set my_entities = [
  'sensor.b1_next_scheduled_backup',
  'sensor.b2_next_scheduled_backup'
] %}
{% set berechnen = my_entities|map('states')|sort|first %}
{{ berechnen }}
{% set berechnen = (as_timestamp(berechnen | replace(" ", "T"))) %}
{{ berechnen }}
{% set berechnen = berechnen | int %}
{{ berechnen }}
{% set berechnen = berechnen | timestamp_custom("%H:%M") %}
{{ berechnen }}

Output is

2024-05-07T10:35:00+00:00

1715078100.0

1715078100

12:35

This is all correct so far. But I cannot calculate anything from hereon.

This works

{{ now() }}
{{ now() - timedelta(minutes=5) }}

2024-05-07 07:50:22.396507+02:00
2024-05-07 07:45:22.396516+02:00

Why won’t this work?

{{ berechnen - timedelta(minutes=5) }}
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

I have tried countless versions of this, none of which worked (so I won’t bother pasting all failed attempts here).

The final code should use a variable via input_number instead of 5 for minutes. And then subtract this value from {{berechnen}}, which, in this case, is 12:35.

Thanks in advance for your help :slight_smile:

What is berechnen at this point?
Which code did you use prior

Because your “12:35” is a string. Subtract the 5 minutes immediately after your first step when berechnen is a datetime string and can be converted to a datetime object with as_datetime.

Or once you have your “12:35”, use today_at:

There’s a timezone difference between the results, of course: up to yoou which you use. Top one is UTC, bottom one is presumably Europe summer time.

1 Like

thank you @Troon

This worked

# (...)
{% set berechnen = my_entities|map('states')|sort|first %}
{% set berechnen = berechnen.split("T")[1].split(":") %}
{% set berechnen = (berechnen[0],":",berechnen[1]) | join %}
{{ today_at(berechnen) - timedelta(minutes=5) }}

There’s most likely a more elegant solution, but this will do :slight_smile:

Yes there is…

Which would be:

{% set berechnen = my_entities|map('states')|sort|first %}
{{ as_datetime(berechnen ) - timedelta(minutes =5)}}

Or like Troon posted

{% set berechnen = my_entities|map('states')|sort|first %}
{{ berechnen | as_datetime - timedelta(minutes =5)}}