Random Time and Duration Generator for Vacation

I’ve seen this request a few places around the forum and was in the process of building my vacation scene so thought I’d share. The following is 2 template sensors that calculate random start times and durations with a few features. You’ll also need to use the Time & Date sensor so that it updates every minute or so with a new random time.

What it does
Generates a random start time and random duration in minutes that you can run in an automation for lights, music etc. to simulate someone is home.

Customizing the start time
It randomizes a start time between a set time and your sunset based on your location with a differential of 45 - 120 mins. So in this example, the start time would be random anywhere between 3:30 and sunset minus (45-120 mins). This means the music could start as early as 1:30pm or as late as 45 minutes before the sun sets.

  vacation_music_start:
    entity_id:
      - sensor.date__time
    value_template: >-
      {% set sunset = as_timestamp(states.sun.sun.attributes.next_setting) | int %}
      {% set earliest_start = (as_timestamp([(now().strftime('%Y-%m-%d')), "15:30:00"]|join(" ")) | int) %}
      {% set random_start = range(earliest_start, sunset)|random %}
      {% set random_offset = range(45, 120)|random | int * 60 %}
      {% set start_time = (random_start - random_offset) | timestamp_custom("%Y-%m-%d %H:%M") %}
      {{start_time}}

Customizing the duration
The next template sensor takes the start time we just created and creates a random duration in minutes but has a hard stop of 10:50pm. This is to prevent music from playing past 11pm breaking a local by-law or something. It also has a minimum duration of 15 mins so the music would play anywhere between 15 minutes and whatever the time is between our start and 10:50pm.

  vacation_music_duration:
    entity_id:
      - sensor.vacation_music_start
    value_template: >-
      {% set start_time = (as_timestamp(states.sensor.vacation_music_start.state) | int) %}
      {% set hard_stop = (as_timestamp([(now().strftime('%Y-%m-%d')), "22:50:00"]|join(" ")) | int) %}
      {% set difference = ((hard_stop - start_time)/60)|int %}
      {% set duration = range(15, difference)|random %}
      {{duration}}

Note, these are just sensors. You will still have to write an automation. If anyone wants a write-up on it, let me know and I will add to this post.

7 Likes