Help setting up a template sensor

Hi Guys,

I am putting together a monitoring dashboard for my houseplants.

I am using an input boolean (input_datetime.rubber_plant_feed_date) to log the date I last fed my plant.
The plant feed bottle will deplete in 4 weeks I would like to create a sensor called “Next Feed Due” which will display countdown in days. For example I installed feed bottle today so this sensor should read “28 Days” When it reaches 1 day I would like it to output “Tomorrow” and “Overdue” once 28 days have past.

thanks in advance

Paste this into the Template Editor to see if the result meets your requirements:

{{ (now().fromtimestamp(state_attr('input_datetime.rubber_plant_feed_date', 'timestamp')).astimezone() - now()).days + 1}}

If it does then you can use it in a Template Sensor:

- platform: template
  sensors:
    next_feed_due:
      friendly_name: Next Feed Due
      value_template: "{{ (now().fromtimestamp(state_attr('input_datetime.rubber_plant_feed_date', 'timestamp')).astimezone() - now()).days + 1}}"

How it works:

All of the following part of the template is simply to convert the input_datetime's value into a timezone-aware datetime object (for demo purposes, I’ll refer to this long-winded bit as “the_future_date”).

 (now().fromtimestamp(state_attr('input_datetime.rubber_plant_feed_date', 'timestamp')).astimezone()

Once we’ve converted it into that form, we can simply subtract today’s date from it.

the_future_date - now()

The result is a timedelta object and we use its days method to get the remaining days.


EDIT

Because we are discarding the timedelta object’s hours portion, and simply using the remaining whole days, the result may be a bit misleading (on the day before the appointed date it will indicate 0 whole days remaining which is correct but not the desired amount we want to see). As a consequence, I’ve altered the template and it now adds 1 day.