Template to show days days / hours passed since switch on?

Hi all

Im trying to add a sensor to my HA that that shows how many days its been since my irrigation has watered a zone on my frontend. I want to monitor the switches for each zone so when it was on last.

I created this template

  - platform: template
    sensors:
      last_greenhouse_watering:
        entity_id: switch.greenhouse # Entity to monitor for changes
        friendly_name: "Last Greenhouse Watering"
        value_template: "{{as_timestamp(states.switch.greenhouse.last_changed) | timestamp_custom('%A %d-%b, %H:%M')}}"

Seems to work fine but it tells me when it was last on as a time rather than how long its been

What it shows - Friday 04-Oct, 09:39
What i want - 1 day 3 hours ago

Im not great at templates so any help would be appreciated

I understand the last changed will get reset when i reboot HA not a huge issue but if there is a better way maybe ? Im using Influx DB

thanks

1 Like

See this thread:

Thanks, not sure whats wrong here, tried to use the code from link

Maybe because its a switch and not a sensor ?

  - platform: time_date
    display_options:
      - 'time'
  - platform: template
    sensors:
      greenhouse_last_connected:
        value_template: >-
          {% set value = states('switch.greenhouse') %}
          {% set last_updated = as_timestamp(strptime(value, "%Y-%m-%d  %H:%M:%S")) %}
          {% set seconds = now().timestamp()-last_updated %}
          {% set hours = seconds / 3600 %}
          {% if seconds / ( 60 * 60 ) > 1 %}
            {{ seconds //  ( 60 * 60 ) }} hours ago
          {% else %}
            {{ seconds // 60 }} minutes ago
          {% endif %}
1 Like

Try this:

- platform: template
  sensors:
    greenhouse_last_changed:
      friendly_name: 'Greenhouse Last Changed'
      entity_id:
        - sensor.time
      value_template: >
        {%- set time = (as_timestamp(now()) - as_timestamp(states.switch.greenhouse.last_changed)) | int  %}
        {%- set minutes = ((time % 3600) // 60) %}
        {%- set minutes = '{}minutes'.format(minutes) if minutes > 0 else '' %}
        {%- set hours = ((time % 86400) // 3600) %}
        {%- set hours = '{}hours '.format(hours) if hours > 0 else '' %}
        {%- set days = (time // 86400) %}
        {%- set days = '{}days '.format(days) if days > 0 else '' %}
        {{ 'Less than 1 minute' if time < 60 else days + hours + minutes }} ago
8 Likes

Awesome that worked prefectly !!!

thanks for taking the time to help me out really appreciate it

1 Like

I can’t take credit for it. :slight_smile:

1 Like

A great example, but it would be correct if it would be possible to incline minutes, hours and days. For example, 1 minute, 2 minutes, 3 minutes, 10 minutes, 1 hour, 2 hours. There is an integration that allows you to incline words. How to insert it correctly here so that you can incline words?

Текст на русском (Text in Russian)

Отличный пример, но было бы правильно, если можно было бы склонять минуты, часы и дни. Например 1 минута, 2 минуты, 3 минуты, 10 минут, 1 час, 2 часа. Есть интеграция которая позволяет склонять слова. Как сюда правильно вставить, чтобы можно было склонять слова?

GitHub - AlexxIT/MorphNumbers: Компонент Home Assistant для работы с числитель

If you follow the link I posted as a source for my template you will see that the original template includes minutes.

I figured it out. This is how it is done. However, this works with the Russian language.

Passed
{%- set time = (as_timestamp(now()) - as_timestamp(states.input_boolean.otpravit_v_telegu.last_changed)) | int %}
{%- set minutes = ((time % 3600) // 60) %}
{%- set minutes = '{} '.format(minutes)|format(morph=‘минута’, as_text=false) if minutes > 0 else ‘’ %}
{%- set hours = ((time % 86400) // 3600) %}
{%- set hours = '{} hours '.format(hours)|format(morph=‘час’, as_text=false) if hours > 0 else ‘’ %}
{%- set days = (time // 86400) %}
{%- set days = '{} days '.format(days)|format(morph=‘день’, as_text=false) if days > 0 else ‘’ %}
{{ ‘Less than 1 minute’ if time < 60 else days + hours + minutes }}

We incline
{{ 1|format(morph=‘минута’, as_text=false) }} 1 minute
{{ 2|format(morph=‘минута’, as_text=false) }} 2 minutes
{{ 4|format(morph=‘минута’, as_text=false) }} 4 minutes
{{ 10|format(morph=‘минута’, as_text=false) }} 10 minutes
{{ 48|format(morph=‘минута’, as_text=false) }} 48 minutes

{{ 1|format(morph=‘час’, as_text=false) }} 1 hour
{{ 2|format(morph=‘час’, as_text=false) }} 2 hours
{{ 4|format(morph=‘час’, as_text=false) }} 4 hours
{{ 10|format(morph=‘час’, as_text=false) }} 10 hours
{{ 48|format(morph=‘час’, as_text=false) }} 48 hours

Текст на русском (Text in Russian)

Разобрался. Делается это так. Правда это работает с русским языком.

image

Прошло
{%- set time = (as_timestamp(now()) - as_timestamp(states.input_boolean.otpravit_v_telegu.last_changed)) | int %}
{%- set minutes = ((time % 3600) // 60) %}
{%- set minutes = '{} '.format(minutes)|format(morph=‘минута’, as_text=false) if minutes > 0 else ‘’ %}
{%- set hours = ((time % 86400) // 3600) %}
{%- set hours = '{} hours '.format(hours)|format(morph=‘час’, as_text=false) if hours > 0 else ‘’ %}
{%- set days = (time // 86400) %}
{%- set days = '{} days '.format(days)|format(morph=‘день’, as_text=false) if days > 0 else ‘’ %}
{{ ‘Less than 1 minute’ if time < 60 else days + hours + minutes }}

Склоняем
{{ 1|format(morph=‘минута’, as_text=false) }}
{{ 2|format(morph=‘минута’, as_text=false) }}
{{ 4|format(morph=‘минута’, as_text=false) }}
{{ 10|format(morph=‘минута’, as_text=false) }}
{{ 48|format(morph=‘минута’, as_text=false) }}

{{ 1|format(morph=‘час’, as_text=false) }}
{{ 2|format(morph=‘час’, as_text=false) }}
{{ 4|format(morph=‘час’, as_text=false) }}
{{ 10|format(morph=‘час’, as_text=false) }}
{{ 48|format(morph=‘час’, as_text=false) }}

Any way to set how many time has passed from the sensor was over a certain value?

Hi,
I think Petro’s Code does the job with less calculations… scroll a few posts to reach the final result

He’s improved it then. As the one I posted was originally from Petro too.

They have different output formats though:

1 Like

I know this is an old thread, but my question is the original one in this thread. I want to get time since an entity was ON. If I look at last_changed, it resets when Home Assistant restarts as the sensor briefly becomes “unavailable”. I have a template binary_sensor and I’d like to compute how long it’s been since it was last ON. Is there a reliable way to do that?

EDIT: Did some digging. I didn’t know about trigger-based template sensors. I created a sensor to store now() based on an appropriate trigger. Then I can compare that sensor’s value to get time elapsed.

For instance, using the Oral B integration, here’s a sensor for when you last brushed your teeth:

  - trigger:
      - platform: state
        entity_id: sensor.toothbrush_toothbrush_state
        to: "running"
    sensor:
      - name: "Last Brushed Teeth"
        unique_id: last-brushed-teeth
        state: "{{now()}}"

For anybody who stumbles on this thread like I did, there is now a native template function available for this! relative_time()

{{ relative_time(states.binary_sensor.g3_instant_motion.last_changed) }}