"Days Until" Template sensor - help needed

image

Edit: Step by step guide to create recurring tasks using these sensors are here: https://smarthomepursuits.com/create-recurring-tasks-in-home-assistant/

I have a template sensor that looks like this. It takes today’s date and shows how many days it’s been since a water filter was last replaced. This works perfectly.

sensor:
  - platform: template
    sensors:
      water_filter_days_since_replacement:
        friendly_name: 'Water Filter Days Since Replaced'
        value_template: >
          {{ ((as_timestamp(now()) - state_attr('input_datetime.water_filters_last_replaced','timestamp')) | int / 86400) | round(0) }}
        icon_template: mdi:clock-end
        unit_of_measurement: 'Days'

I also have a 2nd template sensor that shows how many days until it needs to be replaced. I’ve hardcoded 90 into the template, but how can I add the value of a Number helper instead?

    sensors:
      water_filter_days_remaining:
        friendly_name: 'Water Filter Days remaining'
        value_template: >
          {{ 90 - ((as_timestamp(now()) - state_attr('input_datetime.water_filters_last_replaced','timestamp')) | int / 86400) | round(0) }}
        icon_template: mdi:clock-end
        unit_of_measurement: 'Days'

You don’t need to do all those timestamp conversions, you can subtract datetime objects.

sensors:
      water_filter_days_remaining:
        friendly_name: 'Water Filter Days remaining'
        value_template: >
          {{  states('input_number.XXXX') | int - (now() - 
          states( 'input_datetime.water_filters_last_replaced') 
          | as_datetime | as_local ).days }}
        icon_template: mdi:clock-end
        unit_of_measurement: 'Days'

Edit: Fixed typo

Thanks for the suggestion, but it’s showing a 'state is undefined' error, but state for the input_number is set to 90.

I have corrected the typo.

Thank you, that worked great! There were two extra }} at the end I had to remove. Exactly what I needed, thanks again.

@djbrooks022 Can you please post your final config? The website you are referring to looks offline. :frowning:

The linked guide is archived on the Internet Wayback Machine.