How to get the when the sun rose last? sun.sun.last changed gets reset with HA restart

Hi All, I tried searching but could not find a solution to this problem.

I have a sensor defined as below for displaying the sunrise time on my dashboard:

  sunrise_time:
    friendly_name: "Sunrise"
    value_template: >
      {% if is_state("sun.sun", "above_horizon") -%}
        {{ relative_time(states.sun.sun.last_changed) }} ago
      {%- else -%}
        At {{as_timestamp(state_attr("sun.sun", "next_rising"))| timestamp_custom ('%I:%M %p') }}
      {%- endif %}

the last changed timestamp of the entity gets reset with HA restart and hence provides the wrong value as you see below.
image

How do I fix this?

1 Like