Ui-lovelace custom:button-card template not work


Why in custom:button-card not work this code

 label: >- 
            {{ relative_time(states.switch.tasmota2.last_changed) }}
- type: "custom:button-card"
          show_state: true
          color_type: card
          color: rgb(23, 65, 97)
          name: Lamp Julian
          icon: mdi:string-lights
          entity: switch.tasmota2
          label: >- 
            {{ relative_time(states.switch.tasmota2.last_changed) }}
          show_label: true
              - color: gray
              - font-size: 9px
              - color: gray
              - font-size: 9px
            - value: 'available'
                - color: green
            - value: 'unavailable'
                - color: white
                - background: #2980b9
                - filter: brightness(40%)
                - color: wihite

I need to read and display the time since last status update in seconds minutes hours …

How to solve this problem ?

relative_time is a jinja2 function, which means it isn’t available from the JS frontend. This is not the exact same use case, but it could be possible to use raw JS (although I haven’t managed to get the state to update once a minute yet). Refreshing the dashboard shows the right duration at least:

  - type: 'custom:button-card'
    entity: switch.biltak_motorvarmare
    name: Motorvärmare
    icon: 'mdi:car'
    show_state: true
    state_display: |
        if (entity.state === 'on') {
          function humanReadableDuration(duration) {
              var hours = Math.floor(duration / 1000 / 60 / 60);
              var minutes = Math.floor((duration / 1000 / 60 / 60 - hours) * 60);

              var result = '';
              if (hours > 0) {
                  result += hours + ' h ';
              return result + minutes + ' min';

          var timeDiff = new Date().getTime() - new Date(entity.last_changed).getTime();
          return 'Stäng av (på i ' + humanReadableDuration(Math.abs(timeDiff)) + ')';
          return 'Lägg på';
1 Like

Here’s a hack for getting the card to refresh every 10th second: https://github.com/custom-cards/button-card/issues/436#issuecomment-782891871

This is exactly what I was trying to figure out (how to show “x mins ago” from an input_datetime). Thank you for sharing!

If I’d need to mimic Jinja2’s relative_time() I’d use JS’s moment().fromNow() function, but it’s not implemented in custom:button-card.
And since this ultra-useful card isn’t maintained anymore, :sob: there’s no chance the moment() will get added.
Is there any other way to come by this?

(I fear expanding @slovdahl’s post to capture days, weeks, months and even years might be quite a heavy load for older devices displaying the frontend? At least in cards still using triggers_update: all.)