I have a sensor that looks in my booking calendar if there is an upcoming booking of any of my houses that i rent out.
Below is the sensor that looks for start_time in the calendar and then turns on this sensor 5 hours before the upcoming booking is suppose to arrive.
(using this to turn on the waterheater)
This works great as long as there is an upcomming booking in the calendar.
But if there is none the state of “states.calendar.house1.attributes.start_time” becomes “None”
And therefor the time calculation wont work.
How do i add an (else if) or (condition) to set this sensor to off if there is no upcomming booking in my calendar?
So correct me if i’m wrong. Does the start time attribute exist when there is no event?
So if the attribute doesn’t exist, this should work:
sensor:
- platform: template
sensors:
house1_occupied:
friendly_name: "House1 5h before arrival"
value_template: >
{% if states.calendar.house1.attributes.start_time is defined %}
{{ 'on' if as_timestamp(states.calendar.house1.attributes.start_time) - as_timestamp( strptime(states.sensor.date__time.state, "%Y-%m-%d, %H:%M" ) ) < 18000 else 'off' }}
{% else %}no appointment
{% endif %}
Otherwise, if the attribute does exist and it equals “None”, then you need to search for the None object being returned as the state. That is simply a quick ‘if x’ situation instead of ‘if x is defined’.
indeed @petro’s solution is more elegant and obviously works, but yes you can nest if end else statements, you just need to remember where you start and where you end