Recording "last time it rained" persistently across restarts

Hi, I’m trying to get an entity that tells me the last time it rained. I have a rain sensor. I’m interested in the last rain time.

For some reason, Home Assistant doesn’t persist last_changed and last_updated across restarts, so I can’t keep track of it that way. I tried abusing an input_datetime to store the last rain when it happens, which does persist across restarts BUT input_datetime doesn’t store timezones (it’s timezone-naive), so you just get a naive time that messes with showing the timestamp as a relative time in Lovelace.

It’s like there’s a perfect storm of things that don’t as expected in Home Assistant that are conspiring to not let me store the last time it rained. (Or the last time anything happened, more generally.)

Is there a nice way to do this? I’m even considering custom components if HA can’t handle this natively, if you have any suggestions.

Because everything changes from unknown or unavailable to a state during a restart.

I’m using a retained mqtt message an mqtt sensor and an automation that you could adapt by using the same automation trigger and condition but change the action to storing your datetime and ignore the sensor. With your rain amount sensor in the trigger and condition obviously.

Screenshot 2022-02-20 at 11-42-47 Overview – Home Assistant

automation

- id: 39c0042d-b0de-4e5a-a212-19a698c707c3
  alias: 'Rainfall Sensor Update'
  trigger:
    platform: state
    entity_id: sensor.hobart_rain_since_9am
  condition:
    - condition: numeric_state
      entity_id: sensor.hobart_rain_since_9am
      above: 0
    - "{{ trigger.from_state.state not in ['unknown', 'unavailable'] }}"
    - "{{ trigger.to_state.state not in ['unknown', 'unavailable'] }}"
    - "{{ trigger.from_state.state != trigger.to_state.state }}"
  action:
    service: mqtt.publish
    data:
      payload: >
        {{ now().strftime('%A %d %b')}}, {{states('sensor.hobart_rain_since_9am') }}mm
      topic: 'home-assistant/variable/last_rainfall'
      retain: true

sensor:

- platform: mqtt
  name: "Last Rainfall"
  state_topic: 'home-assistant/variable/last_rainfall'
  value_template: "{{ value }}"
  qos: 0
1 Like

Thanks! After making the post I started using a template sensor based on the input_datetime with an added timestamp, but the MQTT publishing thing you suggested is a better and more stable way to do it, so I’ve switched to it. Works great!

For the “changes from unknown to unavailable” thing, that shouldn’t even happen. It’s the opposite of what the vast majority of people would expect to happen, and it’s the more inconvenient choice. Restarts shouldn’t have any effect on the state of things and erase last_changed information. Hopefully they fix it (just noticed it’s the most upvoted request on the What The Heck? forum) at some point.

Unlikely. Have a read of this topic: https://community.home-assistant.io/t/persistence-of-state/392185/7?u=tom_l