First in a list of dates?

I am trying to create a single sensor for my irrigation system next watering time. Each zone has it’s own time so I wrote a template sensor to sort and take the first. This returns a “unknown” even though both sensors have a date for their next event. I also tried using the min function but same result.

{{sort(states(‘sensor.1_next_cycle’), states(‘sensor.5_next_cycle’) | first)}}

What is wrong with my code or is there a better way to do this.

Appreciate the help.

Do your sensor’s entity_ids actually have “next_cycle” repeated multiple times?

For clarity, I have shortened the entity_ids (change them in the template if they’re actually longer)

{{ [states('sensor.1_next_cycle'), states('sensor.5_next_cycle')] | sort | first }}

If the sensors contain numbers, use the float filter.

{{ [states('sensor.1_next_cycle')|float(0), states('sensor.5_next_cycle')|float(0)] | sort | first }}

The easiest way to test the template is to copy-paste it into the Template Editor.


EDIT

Here’s another way to do the same thing (assumes sensor values aren’t numbers, otherwise float is needed):

{{ ['sensor.1_next_cycle','sensor.5_next_cycle']
  | map('states') | sort | first }}
1 Like

If those sensors have dates, they will need to be converted from strings to datetime objects before sorting. You could also use min instead of sorting and picking the first. Based on Taras’ suggestion:

{{ ['sensor.1_next_cycle','sensor.5_next_cycle']
  | map('states') | map('as_datetime') | min }}

Worked great, thanks!

@ams123

Did you try what I posted?

If the datetime strings have the same format, they don’t need to be converted to datetime objects.

Yes your edit works as well. Thanks!

You’re welcome!

Seeing that it was first to provide you with a detailed explanation and a working solution, please consider marking my post above with the Solution tag.

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

Ah, good point I didn’t consider. I should take a few more moments before assuming you’ve missed something :laughing: