How to calculate hours in Automation depending on sensor

I’m trying to figure out how to get an “hours, minutes ago” value when I create an action.
I have a sensor with a DD/MM/YYYY HH:MM value, which I struggle to get an hours, minutes value from, compared to the current date/time.

I see some topics with this case, but it all has different DD/MM values at this point

I already have this template setup:

- platform: template
    sensors:
      cat_feed_last_time:
        friendly_name: 'Cat Feed Last Time'
        value_template: '{{ states("input_text.cat_feed_last_time") }}'

If it’s possible to get the “hours, minutes ago” input as an attribute on this sensor, what would also be good

Edit: most of it I have figured out, however i’m struggling to transform DD/MM/YYYY to YYYY-MM-DD

- platform: template
    sensors:
      cat_feed_last_time:
        friendly_name: 'Cat Feed Last Time'
        value_template: '{{ states("input_text.cat_feed_last_time") }}'
        attribute_templates:
          relative: >
            {% set x = strptime( states("input_text.cat_feed_last_time"), "%d/%m/%Y %H:%M", now())|as_local %}
            {% set td = (now() - x).total_seconds() %}
            {% set hour = (td//3600)|int%}
            {% set min = (td / 60 )|int - (hour*60)  %}
            {{hour}} hours, {{min}} minutes ago

Thanks, that will get me somewhere :slight_smile:

I was also trying to get a more local text format based on the input_text sensor:

{% set months = ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December'] %}
{{ as_timestamp(states('input_text.cat_feed_last_time')) | timestamp_custom('%d') ~ ' ' ~ months[as_timestamp(states('input_text.cat_feed_last_time')) | timestamp_custom('%m') ] }}

But i’m getting “UndefinedError: ‘list object’ has no attribute ‘08’”

You would need to convert it to an integer to use it to slice the list… or you can use the same strptime() method I used above to convert your helper into a datetime object then go from there:

{% set x = strptime( states("input_text.cat_feed_last_time"), "%d/%m/%Y %H:%M", now())|as_local %}
{% set months = [ 'Januari', 'Februari', 'Maart', 
'April', 'Mei', 'Juni', 
'Juli', 'Augustus', 'September', 
'Oktober', 'November', 'December' ] %}
{{ x.day~ ' ' ~ months[x.month] }}

Hmmm, i’m getting this error:

Invalid config for [sensor.template]: [attributes] is an invalid option for [sensor.template]. Check: sensor.template->sensors->cat_feed_last_time->attributes. (See ?, line ?).

Sorry… it’s been a while since I set up a legacy-style sensor… you will need to use attribute_templates: instead of attributes:. I have corrected it above.

I see! :slight_smile:

I used this method before, things change…

Works as a charm right now. Think I have to transform the templates to the new standard soon, as they will most likely be deprecated at some point.

Thanks again :slight_smile: