Performing date math in template helper

I’m having an issue using a template helper and adding a year to a date.

Background - I have a Kohler generator with the OnQue system, and I’m using the OnQue integration to read the data. When I do generator maintenance, the OnQue integration does not return the date or hours when the maintenance was performed. So I’ve added two helpers which I will manually update when the maintenance is performed:

  1. input_datetime.generator_maintenance_performed_date which is a date/time helper.
  2. input_number.generator_maintenance_performed_hours which is a number helper.

On a dashboard, I want to show the hours or date that the maintenance is due (every 150 hours or yearly). I’ve created template helpers for each of these. I have the hours one working, but I can’t get the date one to return the next year.

In developer tools | Templates, I created this template which works properly:

{% set datetime = as_datetime(states('input_datetime.generator_maintenance_performed_date')) %}
{{datetime.replace(year=datetime.year+1)|as_datetime}}

However, in the helper that I’ve created, it is always returning “Unknown”.

Can anyone help me get this helper working properly?
Thanks!

That last datetime is superfluous, but shouldn’t have prevented the template from resolving. Try this anyway:

{% set datetime = as_datetime(states('input_datetime.generator_maintenance_performed_date')) %}
{{datetime.replace(year=datetime.year+1)}}

I get the same result (works in Dev Tools | Template, but not in the helper). Note that I was initially doing this, and tried adding that just in case it helped.

Try this version (works on my system in a Template Sensor helper).

{{ (states('input_datetime.generator_maintenance_performed_date') | as_datetime + timedelta(days=365)).date() }}
1 Like

Okay, this works (well, except for when adding the 365 days would include a Feb 29th, but this is close enough for me).

Thanks Taras!

1 Like