I have a template sensor that combines two dict lists containing hours and the electricity price for that hour.
Here I create a list of just the next 18 hours, sorted by how cheap the value variable is:
attribute_templates:
nextCheapHours: >
{% set timeIn18h = now() +timedelta(hours=18) %}
{% set nordpoolToday = state_attr('sensor.nordpool_kwh_fi_eur_3_095_024', 'raw_today') %}
{% set nordpoolTomorrow = state_attr('sensor.nordpool_kwh_fi_eur_3_095_024', 'raw_tomorrow') %}
{% set nordpoolCombined = (nordpoolToday + nordpoolTomorrow) %}
{% set nordpoolNext18h = nordpoolCombined | rejectattr('value', 'in', [None]) | rejectattr('start', 'lt', now()) | rejectattr('start', 'gt', timeIn18h) | sort(attribute='value') | list %}
{% set cheapHoursNext18h = (nordpoolNext18h | map(attribute='start')) | list %}
{{ cheapHoursNext18h }}
This becomes a pretty list of datetime.datetime() objects:
[datetime.datetime(2022, 11, 17, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Helsinki')),
datetime.datetime(2022, 11, 17, 3, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Helsinki')),
...................and so on until the last...................
datetime.datetime(2022, 11, 16, 20, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Helsinki'))]
If I did this all in Developer Tools > Template I can easily pick one of the datetimes from the list:
{{ cheapHoursNext18h[0] }}
Which returns:
2022-11-17 00:00:00+02:00
Nice! Thats what I wanted…
BUT! The problem is when I use the sensor… Lets say I want the first datetime from the list… How do I get it to datetime again?
{% set hours = state_attr('sensor.nordpool_next_18h', 'nextCheapHours') %}
{{ hours }} <-- This returns, **as a string**, exactly the same pretty list of datetime.datetime objects.
{{ hours[0] }} <-- This returns the first char of the string so [
Any help appreciated!