Creating a Template to find the 'next date' of a list of attributes

i created a sensor.holidays entity with a list of attributes:

new_years: 2025-01-01
valentines: 2025-02-14
independance_day: 2025-07-04
halloween: 2024-10-31
thanksgiving: 2024-11-28
christmas: 2024-12-25

which could add more as i decide or determine…

however what i want is for the state of that sensor to display the name of the attribute with the ‘next date’ coming up. is there a way to do that!? i’ve been all over AI and the results come up with nothing…

each of these sensors is templated like this:

        {% set today = now().date() %}
        {% set year = now().year %}
        {% set holiday = (now().replace(month=1, day=1)).date() %}
        {% if today > holiday %}
          {% set year = year + 1 %}
          {% set holiday = (now().replace(year=year, month=1, day=1)).date() %}
        {% endif %}
        {{ holiday }}

with the exception of thanksgiving since that changes on a regular basis, but i always want the state to display the next holiday based on the date for each attribute

I would create another attribute which holds the next holiday date and then place each date in an array. Use your logic to add +1 year to each holiday that has already passed, sort the array using reverse=true (I might be wrong about reverse=true, experiment with it) and the first element in the array should be the next upcoming date, set that to the next_holiday attr.

Or create a template sensor that returns the next holiday date using that same logic.

{% set date = now().date() | string %}
{{ states['sensor.xyz'].attributes.items() | selectattr('1', '>=', date) | sort(attribute='1') | map(attribute='0') | first | default(none) }}

if it’s in your template entity…

{% set date = now().date() | string %}
{{ this.attributes.items() | selectattr('1', '>=', date) | sort(attribute='1') | map(attribute='0') | first | default(none) }}
1 Like

thank you so much. that worked briliantly… and much shorter than anything AI was spitting out… i wish i could get a grasp on jinja better… every time i think i know what’s going on… something throws me off…

1 Like