Hi everyone. I want to get my sensor.sunrise and sensor.sunset to stay in sync with the date. The sunrise and sunset time is based in a longitude and longitude that I set in configuration.
Yesterday (6), the sunrise time is 7:01 and sunset time is 20:31.
Today (7) the sunrise time is 7:02 and sunset time is 20:30.
Tomorrow (8), the sunset time will be 20:29.
Right now in Home Assistant frontend, the sunrise time is 7:02 and sunset time is 20:29.
Couldn’t Home Assistant write the sunrise and sunset time to a MySQL database? Here’s my MySQL statement:
SELECT DISTINCT
DATE_FORMAT(convert_tz(last_updated,"Etc/UTC",
"America/New_York"),"%Y-%m-%d") as date,
convert_tz(last_updated,
"Etc/UTC","America/New_York") AS last_changed,
state, entity_id
FROM states
WHERE entity_id = "sensor.sunrise" OR entity_id = "sensor.sunset"
GROUP BY state
ORDER BY date, entity_id;
A MySQL query outputs the following table:
+------------+---------------------+-------+----------------+
| date | last_changed | state | entity_id |
+------------+---------------------+-------+----------------+
| 2018-08-05 | 2018-08-05 21:40:48 | 07:01 | sensor.sunrise |
| 2018-08-05 | 2018-08-05 21:40:48 | 20:31 | sensor.sunset |
| 2018-08-06 | 2018-08-06 20:31:37 | 20:30 | sensor.sunset |
| 2018-08-07 | 2018-08-07 07:02:00 | 07:02 | sensor.sunrise |
| 2018-08-07 | 2018-08-07 20:30:46 | 20:29 | sensor.sunset |
+------------+---------------------+-------+----------------+
I’ve been thinking of this:
SELECT DISTINCT
DATE_FORMAT(convert_tz(sunrise.last_changed,"Etc/UTC",
"America/New_York"),"%Y-%m-%d") as sunrise_date,
sunrise.state, sunset.state
FROM states sunrise, states sunset
WHERE sunrise.entity_id = "sensor.sunrise" AND sunset.entity_id = "sensor.sunset"
GROUP BY sunrise.state;
…which produces:
+--------------+-------+-------+
| sunrise_date | state | state |
+--------------+-------+-------+
| 2018-08-05 | 07:01 | 20:31 |
| 2018-08-07 | 07:02 | 20:31 |
+--------------+-------+-------+
However, that’s innacurate.
I should probably start a thread over in the database forum, but based in the first two rows, I’ve been thinking:
Can I have Home Assistant update the sunrise and sunset time after midnight? The second MySQL query can work if I can update the last_updated and last_changed column for the sensor.sunrise and sensor.sunset.
This is the sensor.yaml configuration that I am using:
- platform: template
sensors:
solar_angle:
value_template: '{{ states.sun.sun.attributes.elevation }}'
friendly_name: 'Sun angle'
unit_of_measurement: 'degrees'
sunrise:
value_template: '{{ as_timestamp(states.sun.sun.attributes.next_rising) | timestamp_custom("%H:%M") }}'
sunset:
value_template: '{{ as_timestamp(states.sun.sun.attributes.next_setting) | timestamp_custom("%H:%M") }}'