Help with sensor template

I want to create a sensor to record gas bottle changes.
I created a helper “number” to record the price. I created a date/time to record the exchange.
I created a button to press to record when the exchange occurs.
I can’t create a template to record the days that have passed since the last exchange.

sensor:

  - platform: template
    sensors:
      dias_ultima_troca:
        friendly_name: "Dias Desde a Última Troca"
        value_template: >
          {{% set last_change = states('input_datetime.ultima_troca_de_garrafa') %}
          {% if last_change != 'unknown' and last_change != 'unavailable' %}
            {% set last_date = strptime(last_change, '%Y-%m-%d %H:%M:%S') %}
            {% set last_date_aware = last_date.astimezone(now().tzinfo) %}
            {% set diff = (now().astimezone(last_date_aware.tzinfo) - last_date_aware).days %}
            {{ diff }}
          {% else %}
            0
          {% endif %}}
       unit_of_measurement: "dias"
       icon: mdi:calendar

What am I doing wrong??Preformatted text

You’re over-complicating it… and based on some of the functions used and the use of the legacy format instead of the current format or Template Helper, I would guess you are using an LLM to “help”.

If you just want whole-days, all you need for the template is:

{{ (now() - states('input_datetime.ultima_troca_de_garrafa')|as_datetime|as_local).days }}

You can copy-paste that directly into the “State template” field if you click Template > Sensor from the Helper Menu.