Custom:button_card - help with converting a jinja template?


I have this jinja template that works in the Dev template checker: Just to produce a duration string since a battery sensor was last seen.

{{ ( as_timestamp(now()) - as_timestamp(states.sensor.freezer_drawer_2_temperature.last_updated)) | timestamp_custom("%Hh %Mm %Ss", false) }}

I’m struggling using it or equivalent code in the button-card templating

Short of making that code a defined sensor, can anyone give me a tip on converting that to JS?

Or can you use Jinja in button-card? I tried and failed.

Many thanks folks :+1:

It’s OK - I managed to find a solution. Yes, it contains some undocumented stuff too, for convenience:

This gives us a duration in seconds (and pretty printed for testing) since a sensor was last seen.

I’ll use this to visually flag dead devices. this._config.entity is a knowing hack so I can shove this in a template. If entity.last_update comes into being at some point (I think I saw @RomRider might have mentioned this) I can use that instead.

button-card tempate:

    var ls = Math.floor(Date.parse(states[this._config.entity].last_updated) /1000);
    var t = states['sensor.current_time'].state;
    var dur = t - ls;
    var h = Math.floor(dur/3600);
    var m = Math.floor(dur/60) % 60;
    var s = dur % 60;

    return "Last seen " + h + ":" + m + ":" + s;

And to make it update live as time ticks by, I created a sensor template:

# Other templates
  - sensor: !include_dir_merge_list local/sensors/
# Current Time in unix epoch seconds, updated every second (or what ever we want)
  - trigger:
      - platform: time_pattern
        # This will update every night
        hours: "*"
        minutes: "*"
        seconds: "/1"
      # Time
      - name: "Current Time"
        unique_id: current_time
        state: "{{ as_timestamp(now()) | int }}"