Jinja set command reverting to initial value in for loop

Hi guys,

I have 4 google calendars and I’m trying to get the most early date. In the code below, earliest_date is always set back to now() in each for iteration. How can I prevent the {% set earliest_date = date %} eventually being reset to the now()?

{% set earliest_date = as_timestamp(now()) %}

{% for item in states.calendar -%}
  {% set date = as_timestamp(item.attributes.start_time) %}

  {% if date > earliest_date %}
    {% set earliest_date = date %}
  {% endif %}        
{%- endfor -%}

Earliest date: {{ earliest_date  | timestamp_custom( "%d/%m/%Y") }}

Or could it be that you have date > earliest_date instead of date < earliest_date?

This is the way jinja works. You cannot pass variables from a loop outside a loop in Jinja2, so this will never work for you no matter what you do.

As annoying as it is, the only solution you have is to hard code your as_timestamps into a list if you truly want to have this functionality using as_timestamp. The reason behind it is that you need to filter your list down, but you have to filter based off the as_timestamp. You cannot pass functions to filters, so that’s why you need to hard code it.

Your other option is to forgo using as_timestamp and just choose the lowest date by sorting, this works with the last_updated attribute, assuming that the format is the same, it will work for start_time. Also, the beauty of doing it this way allows you to get the name of the event as well.

{% set my_dates_sorted = states.calendar | sort(attribute='attributes.start_time') %}
{% set date = as_timestamp(my_dates_sorted[-1].attributes.start_time) | timestamp_custom( "%d/%m/%Y") }
Earliest date: {{ date }}

To clarify, the list that is return will be sorted by oldest to newest. So get the last item in the list by using [-1].

To get other attributes out of the objects, just get other crap out by changing your attribute:

{{ set description = my_dates_sorted[-1].attributes.description }}

Perfect, that works for me!

Highly appreciate the help :wink:

I think you may need to adjust the index. I was thinking about this and I think for you, you’ll want the first item in the list. I was using last_triggered and looking at past events. YOu’ll be looking at future events, so I think the index you should use is 1 not -1. Just an FYI