How to get max temperature for today from forecast?

Hi vingerha (or anyone else), is this for the current day or the coming 23 hours and 59 minutes?

Sorry, found it… → for the current day :blush:

Current day. And the proper way to actually get it would be to use todays date + 1 day.

template:
  - trigger:
      - platform: state
        entity_id: weather.openweathermap
      - platform: homeassistant
        event: start
      - platform: event
        event_type: event_template_reloaded
    action:
      - service: weather.get_forecasts
        data:
          type: hourly
        target:
          entity_id: weather.openweathermap
        response_variable: result
    sensor:
      - name: Max Hourly Temperature
        unique_id: max_hourly_temperature
        device_class: temperature
        unit_of_measurement: °F
        state: >
          {% set midnight = (today_at() + timedelta(days=1)).isoformat() %}
          {{ result['weather.openweathermap'].forecast | selectattr('datetime', 'lt', midnight) | map(attribute='temperature') | list | max }}
2 Likes

Hi Petro, thanks for jumping in!
Would you mind explaining briefly why this is the proper way?
TIA

Replacing hours/minutes on a datetime object can lead to unforeseen issues if you don’t have the correct timezone. It’s best to use the template methods that we added to make time calculations easier.

The issue is, most forum posts use old methods which run into issues with timezones, leading to undesired effects.

You should avoid using .replace if you can. You should avoid using as_timestamp if you can.

Both can be supplimented with timedelta which is essentially a duration. YOu can add and subtract them from datetimes. If the datetime has a TZ attached to it, you can assume that it will be the correct time in your TZ regardless what TZ the datetime is in.

1 Like

I tried this and it shows UndefinedError: ‘result’ is undefined. Everything else seems to be ok in there. Not sure what it doesn’t like. I can call the service manually on the service tab just fine.

You have to configure that entire chunk of code in your configuration file, not in a UI template sensor.

1 Like

Petro,

Thanx for your help!

Did you get it working?