How to get max temperature for today from forecast?

I have OpenWeatherMap integration set up, which has attributes as:

...
visibility_unit: km
precipitation_unit: mm
forecast:
- condition: cloudy
  precipitation_probability: 0
  datetime: '2022-12-20T18:00:00+00:00'
  wind_bearing: 16
  temperature: -0.3
  pressure: 1024
  wind_speed: 1.01
  precipitation: 0
- condition: cloudy
  precipitation_probability: 0
  datetime: '2022-12-20T21:00:00+00:00'
  wind_bearing: 123
  temperature: -1.7
  pressure: 1021
  wind_speed: 1.87
  precipitation: 0
...

Now I want to filter the array ā€œforecastā€ on datetime = today (datetime.strftime(%f) == now().strftime(%f) would do), select temperature, and get max value.

This is not only for this specific date, but to learn how to work with arrays where you want to filter on one property, select another, and then run some function on it to return single value. I will then use this logic on different sensors than weather, too.

In C# LINQ, Iā€™d do something like
states.weather.openweathermap.forecast.Where(item => item.datetime.Date == DateTime.Today).Select(item => item.temperature).Max(),
but with templates/jinja2, Iā€™m lost.

1 Like

Maybe Iā€™m wrong but it seems to me that the max temperature for today is already populated

{{ states.sensor.openweathermap_forecast_temperature.state }}

That will not help you if you need something else from the forecast section but itā€™ll help you with that specific ā€œTodayā€™s maximum temperatureā€ issue.

I believe @Olivier1974 has a point, else it is

{{ state_attr('weather.openweathermap', 'forecast')| map(attribute='temperature') | list | max }}

forgot the date component

{{ (state_attr('weather.openweathermap', 'forecast')|selectattr('datetime', 'lt', (now().replace(hour=23,minute=59)).isoformat()))| map(attribute='temperature') | list | max }}
3 Likes

Thanks @Olivier1974 , that does it for the max value, wihch is good for this case. And I really appreciate @vingerha 's code, as that allows me to do a lot more stuff now, thank you both :+1:

1 Like

Perfect. Made my day!

Hi! That doesnā€™t work after todays update any more. Can you help?

From 2024.4 the sensor-based forecasts are deprecated ā€¦you need to create them yourselves now
Weather - Home Assistant (home-assistant.io)

Thanks! (but actually I donā€™t have a clue, how to code that)

The example for Template doesnā€™t work. ā€œHourly Not definedā€

Without details I have no clue how to comment
EDIT: where and how did you add that template?

I tried some examples in the Template Editor:

Actually I tried to get the daily max. temperature (21C)

from the Met.no- Integration

Ich lese anscheinend den Max.-Wert der folgenden Stunde. Wie komme ich an den Tages-Max-Wert?

I cannot guess which sensor you use in which card butā€¦
the weather sensor by met.no only delivers one (1) temperature and I am not sure if this is sort-of-current or max, I guess it is current as it shows 12.9
Hence you would need to create the forecast/template sensor as per above link. On top of that you can run a script to extract the max value

1 Like

I am really grateful for all the answers and tips, but I am not able to create the solution.
Here is a screenshot after I tapped on the card. The sensor is called Home from Met.no and generates the forecast data (hourly or next days).
I have never written a script before and I canā€™t get any further with the examples from the links.

I understand the challenge but (always a but) knowing how to create Template sensors is sort of an important part when using HA. I also understand the learning curve and will provide some support but as I am travelling till Thu, it will have to wait till later this week (unless someone else steps in)

If ever you want to try beforeā€¦what needs to be done

  • create a Template sensor to collect the forecast via service call (above link). The card you show is using a service call to generate the hourly/daily forecast data bit this is only used in the card, hence you need a separate entity to have the forecast data in its attributes
  • any calculations as to the ā€˜maxā€™ or ā€˜minā€™ or ā€¦ , for this you need another Template entity which will use the forecast entity content to extract the required value, this reuqires a small jinja script. An alternative is that you use the very same jinja script directly in a card, saves the additional entity. But I am not sure what you want to achive, only 1 max value or a list or graph ?

I have used some time today trying to figure out this my self, and have made this that will give you:

  • A sensor for daily forecast
  • A sensor for hourly forecast
  • A sensor for the highest temperature in the current day
  • A sensor for the lowest temperature in the current day

Just change weather.hjem for your weather entity and add this in your configuration.yaml
(Iā€™m no expert, so there might be some thing that should be done different, but this works for me)

template:
  - trigger:
      - platform: state
        entity_id: weather.hjem
      - platform: homeassistant
        event: start
      - platform: event
        event_type: event_template_reloaded
    action:
      - service: weather.get_forecasts
        data:
          type: daily
        target:
          entity_id: weather.hjem
        response_variable: daily
    sensor:
      - name: Forecast Daily
        unique_id: weather_forecast_daily
        state: "{{ states('weather.hjem') }}"
        attributes:
          forecast: "{{ daily['weather.hjem'].forecast }}"

  - trigger:
      - platform: state
        entity_id: weather.hjem
      - platform: homeassistant
        event: start
      - platform: event
        event_type: event_template_reloaded
    action:
      - service: weather.get_forecasts
        data:
          type: hourly
        target:
          entity_id: weather.hjem
        response_variable: hourly
    sensor:
      - name: Forecast Hourly
        unique_id: weather_forecast_hourly
        state: "{{ states('weather.hjem') }}"
        attributes:
          forecast: "{{ hourly['weather.hjem'].forecast }}"
    
  - sensor:
      - name: "High temperature today"
        device_class: temperature
        state: "{{ (state_attr('sensor.forecast_hourly', 'forecast')|selectattr('datetime', 'lt', (now().replace(hour=23,minute=59)).isoformat()))| map(attribute='temperature') | list | max }}"

  - sensor:
      - name: "Low temperature today"
        device_class: temperature
        state: "{{ (state_attr('sensor.foreceast_hourly', 'forecast')|selectattr('datetime', 'lt', (now().replace(hour=23,minute=59)).isoformat()))| map(attribute='temperature') | list | min }}"

EDIT:
After feedback from petro I have changed the high and low temperature sensors.
Keeping the old code so the rest of the thread still makes sense :slight_smile:

New code for the sensors:

  - sensor:
      - name: "High temperature today"
        unique_id: High_temperature_today
        device_class: temperature
        unit_of_measurement: Ā°C
        state: >
          {% set midnight = (today_at() + timedelta(days=1)).isoformat() %}
          {{ state_attr('sensor.forecast_hourly', 'forecast')| selectattr('datetime', 'lt', midnight) | map(attribute='temperature') | list | max }}

  - sensor:
      - name: "Low temperature today"
        unique_id: Low_temperature_today
        device_class: temperature
        unit_of_measurement: Ā°C
        state: >
          {% set midnight = (today_at() + timedelta(days=1)).isoformat() %}
          {{ state_attr('sensor.foreceast_hourly', 'forecast')| selectattr('datetime', 'lt', midnight) | map(attribute='temperature') | list | min }}

6 Likes

Greatā€¦as it worksā€¦ you should be happy :slight_smile:

Great, I would never have been able to put that together! Thank you very much!

Many thanks also to you for your time, help and explanations

This also helped me a ton, thanks so much!
There was a small typo with ā€œforceastā€ instead of ā€œforecastā€, but it was easy to fix. :blush:

Great Work, thanks