Anniversaries to template help

hi everyone, i need some help as i have no idea how to write code. so im using “Anniversaries” intergration to keep track of when a pet passed away. it worked untill a year passed and now it started to count from 1 again. can anyone help with writing a template as i really hyave no idea how to do that. i need it to count years and months ideally. not too bothered about days or weeks

Hi, you can use the calendar that HA has and from there, with an automation, you can achieve a lot depending on your needs.
That way you don’t need a custom integration, which is another advantage.

ok thank you. tbh i have tried using ChatGTP and i got this…

it show crrectly in the template editor. but when i search for it in the states tab it comes up with 4 years 4 months… so close lol

  • platform: template
    sensors:
    years_and_months_since:
    friendly_name: “Bubbles Passed Away”
    value_template: >-
    {% set start_date = strptime(‘2020-01-01’, ‘%Y-%m-%d’) %}
    {% set current_date = now() %}
    {% set years = current_date.year - start_date.year %}
    {% set months = current_date.month - start_date.month %}
    {% if months < 0 %}
    {% set years = years - 1 %}
    {% set months = months + 12 %}
    {% endif %}
    {{ years }} years and {{ months }} months

Unless you want to spend a ton of time calculating the months, I suggest you move to years and weeks or years and days.

Thank you, yes i have changed it to display years and days.

does that mean you’re all set? or do you still need help?

yes thank you its all set. not sure about the decimal point but i can live with it, thanks

…is terrible at HA code. It gave you an overly-complex legacy format template. Try this, which will “scale”:

template:
  - sensor:
      - name: "Bubbles passed away"
        state: "{{ time_since('2020-01-01'|as_datetime, precision=2) }}"

1-Jan-2024 currently shows as “5 months 15 days”; 1-Jan-2020 as “4 years 6 months” (because it’s just over 5.5 months). It does have a slight quirk, though: it’ll show “x years 12 months” in the two weeks before the x+1 anniversary. You can get around that with:

"{{ time_since('2020-01-01'|as_datetime, precision=3).split(' ')[:4]|join(' ') }}"

which removes any rounding in the second unit.

time_since and as_datetime are documented here: