So, I’m trying to wrap my head around writing yaml files, but it’s a bit slow. Right now I’m trying to create three binary sensors for determining wether it’s dawn day or evening, based on a couple of factors. I’ve started with the Dawn one.
Dawn is to be determined by if the time i either 05:15 in the morning or two hours before sunrise (whichever is the latest) and until sunrise. I might tweak this later when I get it working. This is my code:
- platform: template
sensors:
is_dawn_time:
friendly_name: "Is it dawn time"
value_template: >-
{% set sunrise = state_attr('sun.sun', 'next_rising') %}
{% set dawn_start = (sunrise - timedelta(hours=2)).time() %}
{% set start_time = max(dawn_start, '05:15') %}
{% set end_time = sunrise.time() %}
{% set now = now().time() %}
{{ now >= start_time and now <= end_time }}
It’s in a separate file, and is included in my configuration.yaml
Line 2 is attempting to subtract a timedelta from a string, which isn’t possible.
Time conversions are always fiddly, with datetime objects, strings and UNIX timestamps — if you still get stuck once you’ve tried it out in the template editor, do ask again.
If you paste this on Developer Tools > Templates you will see the error is related to different variables types, as pointed by @Troon.
This should work:
{% set sunrise = state_attr('sun.sun', 'next_rising') %}
{% set dawn_start = (((sunrise | as_datetime) - timedelta(hours=2)).time()) | string %}
{% set start_time = max(dawn_start[0:8], '05:15:00') %}
{% set end_time = (sunrise | as_datetime).time() | string %}
{% set now = (now().time() | string)[0:8] %}
{{ now >= start_time and now <= end_time }}
However, as @Troon also mentioned, playing with all those conversions between string and datetime is tricky and your code will be quite fragile.
There is an custom integration called Sun2 which I’m pretty sure will have this sensor you are looking for, but if you want to do the calcs yourself, I would use sun elevation instead, as dawn is defined by that:
Thanks! I think I’m gonna check out the Sun2 integration. That might help a lot, and I would have to mess with my own calculations… though I’m probably gonna need to learn.