Hello dear community,
I have a question about the handling of attributes of entities that I am not getting anywhere with. Maybe someone can help me?
I have various weather entities, some of which have long-term forecasts. I would like to select a certain time range from the forecast, which is stored as an attribute in the entity. To make my request easier to understand, I will use “weather.homeassistant_hourly” as an example.
As you know, the attributes of weather.homeassistant_hourly look like this:
temperature: 13.9
humidity: 83
pressure: 1023.8
wind_bearing: 207
wind_speed: 5.4
forecast:
- condition: sunny
precipitation: 0
temperature: 16.4
datetime: '2022-06-10T07:00:00+00:00'
wind_bearing: 202.6
wind_speed: 5.8
- condition: sunny
precipitation: 0
temperature: 18.8
datetime: '2022-06-10T08:00:00+00:00'
wind_bearing: 209.3
wind_speed: 6.8
...
I know that the following template can be used to read out the various attributes under “forecast”:
{{ state_attr('weather.homeassistant_hourly', 'forecast')
| map(attribute='datetime')
| list
}}
This results in a list
[
"2022-06-10T07:00:00+00:00",
"2022-06-10T08:00:00+00:00",
...
]
But I want to select a certain time range. Unfortunately, it is not possible for me to make a date comparison with the datetime attribute. The only possibility I can think of is to narrow it down using:
| selectattr('datetime', 'search', 'STRING')
| rejectattr('datetime', 'search', 'STRING')
However, this is very inelegant and quickly becomes spaghetti code when using the forecast for several days.
Is there a way to recycle the entity string under “datetime” as a datetime? I would like to be able to execute something like the following, for example:
{{ state_attr('weather.homeassistant_hourly', 'forecast')
| selectattr('datetime', '>', now())
| map(attribute='datetime')
| list
}}
This results in the error message
TypeError: '>' not supported between instances of 'str' and 'datetime.datetime'