Trigger automation 15 minutes before date_time stored in input_datetime

Tags: #<Tag:0x00007f77f8597028>

Okey, I have this in my configuration.yaml file:

sensor:
  - platform: time_date
    display_options:
      - 'time'
      - 'date'
      - 'date_time'
      - 'date_time_iso'
      - 'time_date'
      - 'time_utc'
      - 'beat'

input_datetime:
  flemming_phone_next_alarm_date_and_time:
    name: Flemmings neste alarm
    has_date: true
    has_time: true

I want to trigger an automation 15 min before the above input_datetime.

Example:
If input_datetime is 2019-11-02 15:45:00 I want the automation to trigger 2019-11-02 15:30:00.
If input_datetime is 2019-11-02 00:05:00 I want the automation to trigger 2019-11-01 23:50:00.

By the way, checking the template I see the formatting of sensor.date_time and my input_datetime is not the same:
{{ states.sensor.date_time.state }} show as 2019-10-30, 13:30
{{ states.input_datetime.flemming_phone_next_alarm_date_and_time.state }} show as 2019-10-30 13:30:00

Tried to google, and I find examples on time and date separate, but not with them together, and with trigger in “past-time”

As you are storing the date in your input datetime it’s actually quite easy. Try this in the template editor:

value_template: >
  {% set alarm_time = as_timestamp(states('input_datetime.flemming_phone_next_alarm_date_and_time')) %}
  {% set time_now = as_timestamp(states('sensor.date_time').replace(',', '')) %}
  {{ time_now >= ( alarm_time - 900 ) }}

Edited: see Phil’s comment below.
Edit2: Removed extra parentheses.

One of the annoying things about sensor.date_time is that you can’t use it directly in as_timestamp() because of the comma. But you can do this:

  {% set time_now = as_timestamp(states('sensor.date_time').replace(',', '')) %}
1 Like

Amended my template. Thanks.

1 Like

Thanks, well, It did not work in the template editor (if it should)
Error rendering template: TemplateSyntaxError: unexpected ‘}’, expected ')'

Actually, I never tried it before (and it might be new), but you can use sensor.date_time_iso directly in the as_timestamp() function.

EDIT: I checked. The date_time_iso option was added in 0.91. Must have overlooked it. :slight_smile:

I think there’s an extra parenthesis in the last line. Try:

  {{ time_now >= ( alarm_time - 900 ) }}

Apologies. There was an extra ( left in front of “time_now…” I missed when cleaning up the template of extraneous junk. Fixed.

Looks better.
This:

value_template: >
  {% set alarm_time = as_timestamp(states('input_datetime.flemming_phone_next_alarm_date_and_time')) %}
  {% set time_now = as_timestamp(states('sensor.date_time').replace(',', '')) %}
  {{ time_now >= ( alarm_time - 900 ) }}

{{ alarm_time }}
{{ time_now }}

Result in this:

value_template: >
  
  
  False

1572705900.0
1572442200.0

Looks ok? What is 900 present? seconds?

Timestamps are in seconds since the epoch date ( January 1, 1970 at 00:00:00).

15 minutes * 60 = 900 seconds.