Countdown till sunset

I need some help. I’m sure it’s an easy configuration, but I am not a programmer, and I couldn’t figure this out till now.
I would like to create a sensor, which shows me, how much time is left till sunset.

Thank you.

Try this:

  - platform: template
        value_template: "{{ relative_time(state_attr('sun.sun', 'next_setting')) }}"

Thank you very much for your response.

Unfortunately, it gives me the “Unknown” value.

P.S. I have the latest version of HA


Ah sorry, relative_time() only works for times in the past. This should do it, but you need a time sensor if you don’t have one already.

  - platform: template
        entity_id: sensor.time
        value_template: "{{ (as_timestamp(state_attr('sun.sun', 'next_setting')) - as_timestamp(now()))| timestamp_custom('%H hours, %M minutes', 0) }}"
  • relative_time converts datetime object to its human-friendly “age” string. The age can be in second, minute, hour, day, month or year (but only the biggest unit is considered, e.g., if it’s 2 days and 3 hours, “2 days” will be returned). Note that it only works for dates in the past .


{{ (as_timestamp(state_attr('sun.sun', 'next_setting')) - as_timestamp(now())) | timestamp_custom('%I:%M',false) }}

It seems to be working for me atm but there’s something wrong with my timezone I think, so I can’t promise it’s right.

@tom_l beat me to it :slight_smile:

1 Like

@eggman Try with %H instead of %I

Tom’s right, should be %H, at the moment it makes no difference 'cos sunset is less than 12 hours away for me, but it would be wrong if it were more than 12.

Thank you very much. Works perfectly.
Thanks for everyone.