Paste this into the Template Editor to understand how the strptime function converts a date represented as a string to a datetime object:
{{ '2020-11-23' }}
{{ '2020-11-23' is string }}
{{ strptime('2020-11-23', '%Y-%m-%d').date() }}
{{ strptime('2020-11-23', '%Y-%m-%d').date() is string }}
The following template takes today’s date and adds one day to it (the result is a datetime object) then compares it to the value of sensor.collection
(after it has been converted to a datetime object).
{{ now().date() + timedelta(days=1) == strptime(states('sensor.collection'), '%Y-%m-%d').date() }}
The template will evaluate to true
only if today’s date is one day before the collection date. It can be used as a Template Condition in an automation:
- alias: 'Example 1'
trigger:
platform: time
at: '18:00:00'
condition:
condition: template
value_template: >
{{ now().date() + timedelta(days=1) == strptime(states('sensor.collection'), '%Y-%m-%d').date() }}
action:
service: notify.whatever
data:
title: 'Recycling tomorrow!'
message: "Put out the recycling this evening for tomorrow's collection."
Alternately, you can use the new abbreviated style of defining a Template Condition:
- alias: 'Example 2'
trigger:
platform: time
at: '18:00:00'
condition: "{{ now().date() + timedelta(days=1) == strptime(states('sensor.collection'), '%Y-%m-%d').date() }}"
action:
service: notify.whatever
data:
title: 'Recycling tomorrow!'
message: "Put out the recycling this evening for tomorrow's collection."
There is also the possibility of using a Template Trigger. It would not need a condition
because the trigger would do both:
- check if the current time is equal to the scheduled time
- check if today’s date is one day before the collection date
It would look something like this:
- alias: 'Example 3'
trigger:
platform: template
value_template: >
{{ now().hour == 18 and now().minute == 0 and now().date() + timedelta(days=1) == strptime(states('sensor.collection'), '%Y-%m-%d').date() }}
action:
service: notify.whatever
data:
title: 'Recycling tomorrow!'
message: "Put out the recycling this evening for tomorrow's collection."
Personally, I prefer Example 2.