Sensor template with day and month

Christmas is coming and my simple automation from last year needs to be better.
My current one only checks if it’s december and in the automation, not in a template.

My plan is to make a sensor template based on now().day and now().month to allow the lights to come on from late november to start january.
From something like 25th november, all of december and to 5th january.
But I’m kind of lost with all the and and or conditions in the template.

Have anyone made something like this before?

- platform: template
  sensors:
    allow_xmas_lights:
      friendly_name: 'Allow xmas lights'
      value_template: >-
        ??
      icon_template: 'mdi:pine-tree'

The tricky part of template sensors based on date/time is getting them to update. You can’t just use now(), because that doesn’t cause state_changed events. You have to use something like the Time & Date Sensor. I’d recommend:

sensor:
  - platform: time_date
    display_options:
      - date

This will create a entity named sensor.date, whose value will be something like '2018-10-12'. And since it’s an entity, it will cause a state_changed event each time it is updated (which, in turn, will cause the template sensor based on it to also update.)

So, you could do something like this:

sensor:
  - platform: template
    sensors:
      allow_xmas_lights:
        value_template: >
          {% set today = states('sensor.date').split('-') %}
          {% set month = today[1]|int %}
          {% set day = today[2]|int %}
          {{ month == 11 and day >= 25 or
             month == 12 or
             month == 1 and day <= 5 }}
1 Like

Please please please do not turn them on until December or I will be forced to seek you out with an anti inappropriate Xmas light rocket.

@pnbruckner
Works like a charm. Thank you very much. Better writen than I ever could.

@nickrout
My xmas lights consist of 1 warm white light chain around the house that doesn’t even blink so it’s pretty discrete :slight_smile:

Hi, it’s possible to have an example of template for christmas light working from 8 December to 6 January? Thanks

sensor:
  - platform: template
    sensors:
      allow_xmas_lights:
        value_template: >
          {% set today = states('sensor.date').split('-') %}
          {% set month = today[1]|int %}
          {% set day = today[2]|int %}
          {{ month == 12 and day >= 8 or
             month == 1 and day <= 6 }}

This, again, assumes sensor.date is formatted as YYYY-MM-DD. Adjust accordingly if not.