Months from a specific date

I would like to calculate the months of my dog, from his birthday to now. I created a sensor but the state returned “unknown”: anyone could help me to know what’s the problem?

  - platform: template
    sensors:
      months_dog:
        value_template: '{{ (as_timestamp(now()) - (states.input_datetime.birthday_dog)) | timestamp_custom("%M")| int }}'
        entity_id: sun.sun

I seen a similar topic (this one) but it’s different from my problem and I don’t know how to use it.

Thanks!

You are mixing timestamp and date… so the answer is unknown.

Here is the example you are referring to modified for your needs (if the date is in the format “YYYY-mm-dd HH:MM:SS” :

{% set date = states('input_datetime.birthday_dog') %}
{% set date = strptime(date, '%Y-%m-%d %H:%M:%S') %}
{% set today = now() %}
{{ today.year*12+today.month - (date.year*12+date.month) }}

So try this:

  - platform: template
    sensors:
      months_dog:
        value_template: >-
                  {% set date = states('input_datetime.birthday_dog') %}
                  {% set date = strptime(date, '%Y-%m-%d %H:%M:%S') %}
                  {% set today = now() %}
                  {{ today.year*12+today.month - (date.year*12+date.month) }}
        entity_id: sun.sun

Thank you folk!

1 Like