Have timestamp (varying day to day), want to use it!

What I want to achieve:
I have a terrarium full of plants that normally reside in tropical or sub-tropical areas. I thought it would be pretty cool to give them a daylight cycle that is the same as some place close to the equator. So I want the lights to turn on when the sun goes up at some specified place and turn off when the sun sets.

What I have done:
I found an open API that gives me sunrise and sunset times as JSON (for some random spot in Africa), here: https://api.sunrise-sunset.org/json?lat=9.757452&lng=16.415384
I use the RESTful integration to “extract” the variables sunrise and sunset respectively to two entities that I call “sensor.sun_tropic_sunrise” and “sensor.sun_tropic_sunset”.

This is where I am lost. I have tried a couple of different ways I found here on the forum, one was using a template for the “action” that had an if-else-clause checking if the current time is before or after sunset and sunrise, setting switch off or on. That partly worked; I got it to print the right switch state but it never triggered. I can’t remember what I set the trigger to… I believe I even tried setting trigger to template sensor.sun_tropic_sunrise == True and still nothing.

I’ve also tried this:

  - platform: time
    at: "{{ as_datetime(states('sensor.sun_tropic_sunset')[:19]) }}"

It doesn’t set it off either.

Any suggestions as to what I should try next?

What does the following return in Developer Tools → Template editor

{{ states('sensor.sun_tropic_sunset') }}
{{ as_datetime(states('sensor.sun_tropic_sunset') }}
{{ as_datetime(states('sensor.sun_tropic_sunset')[:19]) }}

Can you also share the configuration of your rest sensors.

Set the device_class of both sensors to timestamp and ensure the reported date and time are in ISO format. This allows them to be referenced directly by a Time Trigger.

  - scan_interval: 3600
    resource: https://api.sunrise-sunset.org/json?lat=9.757452&lng=16.415384 2
      - name: 'Sun Tropic Sunrise'
        device_class: timestamp
        value_template: "{{ today_at(value_json.results.sunrise[:-3]).isoformat() }}"
      - name: 'Sun Tropic Sunset'
        device_class: timestamp
        value_template: >
          {{ today_at(strptime(value_json.results.sunset,'%I:%M:%S %p').strftime('%H:%M:%S')).isoformat() }}
alias: example
  - platform: time
    at: sensor.sun_tropic_sunset
condition: []
  ... etc ...

Reference: Time Trigger


Correction. Template for sunset now correctly converts PM to 24-hour time.

That code gives this response: (Result type: string)

2023-03-23 17:06:09+00:00
2023-03-23 17:06:09+00:00
2023-03-23 17:06:09

My rest sensors configuration looks like this:

  - platform: rest
    name: Sun_tropic
      - results
    value_template: "{{ as_datetime(value_json['results']['sunrise'].title()) }}"
    resource: https://api.sunrise-sunset.org/json?lat=9.757452&lng=16.415384&formatted=0
  - platform: template
        friendly_name: "Sunrise tropic"
        value_template: "{{ as_datetime(state_attr('sensor.sun_tropic', 'results')['sunrise'].title()) }}"
        entity_id: sensor.sun_tropic
        friendly_name: "Sunset tropic"
        value_template: "{{ as_datetime(state_attr('sensor.sun_tropic', 'results')['sunset'].title()) }}"
        entity_id: sensor.sun_tropic

Thank you! That looks like a good solution. Will try it when I have more time and energy.

As an alternative, I use sun2, and create a binary sensor with this config:

- platform: sun2
  latitude: 9.757452
  longitude: 16.415384
  elevation: 163
  time_zone: <as required>
    - elevation: 
        above: -0.833
        name: Daytime

Then it’s very easy to create a simple automation from this:

- id: run_scene_at_sunset
  alias: Turn on lights at sunset
  - platform: state
    entity_id: binary_sensor.daytime
    from: 'on'
    to: 'off'
  condition: []
    blah blah

sun2 allows you to adjust how you define day and night in various ways - I use elevation as it’s most accurate for lights where I live, but you may want to tune it as you see fit.

How does sun2 know it’s supposed to track the sun’s position? Does adding the features latitude, longitude, elevation and time_zone make home assistant automatically treat it as a sun “object” at the given location?

Yes, sun2 is a specific custom component to do just this - I linked it above. Install in custom_components or via HACS or whatever.

Oh, I missed the link.

I used this last night and this morning the light went on just as planned! Thanks! BTW I added a timedelta to get it from UTC to my time by appending this:

..... .isoformat() + as_timedelta('02:00:00')

I’m sure the sun2 as recommended below would work just as well, but this is the one I went for.

You’re welcome but it appears you have misunderstood the purpose of the Solution tag.

You marked your own post with the Solution ta using the solution I had suggested. It’s the community’s custom to assign the Solution tag to the first post that answers/resolves the original question/problem.

For more information, refer to guideline 21 in the FAQ.

I just mis-clicked. :grinning_face_with_smiling_eyes: Corrected.

1 Like