I like knowing the timing of sunrise and sunset. Beyond the mere awareness of daylight hours, understanding when the sun will rise and set offers a multitude of practical benefits. From optimizing energy consumption and enhancing home automation routines, to planning outdoor activities and fostering a connection with nature, having real-time information about sunrise and sunset adds a layer of intelligence to our environments. Getting home before dark is a lot easier when you have your time limit down to the minute.

All that said, displaying the "Sun Next rising" or "Sun Next setting" outputs a full datetime (e.g. "March 8, 2024 at 6:21 AM"), when really all I want to see is the timestamp (e.g. 6:21 AM). The following code changes solve this!

Step 1: Open your configuration.yaml file

template:
  - sensor: !include template_sensors.yaml

This sets up the template sensor integration and includes the sensors defined in template_sensors.yaml.

Step 2: Create or edit your template_sensors.yaml file

# Sun Integration Attributes
  - name: "Next Sunrise"
    unique_id: "next_sunrise"
    state: '{{ as_timestamp(states.sun.sun.attributes.next_rising) | timestamp_custom(" %I:%M %p") | replace(" 0", "") }}'
    icon: mdi:weather-sunset-up

  - name: "Next Sunset"
    unique_id: "next_sunset"
    state: '{{ as_timestamp(states.sun.sun.attributes.next_setting) | timestamp_custom(" %I:%M %p") | replace(" 0", "") }}'
    icon: mdi:weather-sunset-down

This file defines two template sensors, "Next Sunrise" and "Next Sunset," using the provided code. The sensors extract the relevant information from the Sun integration and format it as desired.

Step 3: Restart Home Assistant

After making these changes, restart your Home Assistant instance to apply the new configuration.

Step 4: Add the Sensors to Your UI

Navigate to your Home Assistant Dashboard, "Edit" it, and then choose "Entities". Search for your newly created sensors ("Next Sunrise" and "Next Sunset") and add them!

Now, you should have the next sunrise and sunset displayed on your Home Assistant dashboard!

Note: Ensure that the Sun integration is correctly configured in your configuration.yaml file for accurate sunrise and sunset information. If needed, refer to Home Assistant documentation for Sun integration configuration options.