Does anyone know how to access things like ālast_changedā within a template? I tried accessing it directly with {{ states.sensor.sensor.last_updated }}, but it gives me a timestamp rather than showing something like 9 minutes ago. Example below, the first is using the Entity card, the 2nd is using a template
{%- set time = (as_timestamp(now()) - as_timestamp(states.device_tracker.car.last_changed)) | int %}
{%- set minutes = ((time % 3600) // 60) %}
{%- set minutes = '{}m'.format(minutes) if minutes > 0 else '' %}
{%- set hours = ((time % 86400) // 3600) %}
{%- set hours = '{}h '.format(hours) if hours > 0 else '' %}
{%- set days = (time // 86400) %}
{%- set days = '{}d '.format(days) if days > 0 else '' %}
{{ 'Less than 1 min' if time < 60 else days + hours + minutes }} ago
Reason being is that it works with multiple days rather than just resetting at 24 hours like most templates you find do.
So for one of my automations would look like this:
{%- set time = (as_timestamp(now()) - as_timestamp(state_attr('automation.batteries_low_notification', 'last_triggered'))) | int %}
{%- set minutes = ((time % 3600) // 60) %}
{%- set minutes = '{}m'.format(minutes) if minutes > 0 else '' %}
{%- set hours = ((time % 86400) // 3600) %}
{%- set hours = '{}h '.format(hours) if hours > 0 else '' %}
{%- set days = (time // 86400) %}
{%- set days = '{}d '.format(days) if days > 0 else '' %}
{{ 'Less than 1 min' if time < 60 else days + hours + minutes }} ago
There is a great template extension from Petro, that works with Jinja (=template) macros. Makes it super easy to work with time things in templates, and saves a lot of code repetition.
Oh! Iām so sorry, I thought you (of all people) would know about this. But itās not that long āon the marketā, not even half a yearā¦ Really if Iād have known, Iād have posted a link earlier.
Itās really a nifty little extension and the idea with Jinja macros is something, Iām thinking about using. Havenāt found something to use it meaningful, but that will not be like that for long.
This is definitely a solution. But the reason i liked my template and now the add-on is because it can returns more complex strings like 6d 4h 23m. Or even seconds if needed
Im a sucker for having all of the info available. But i can definitely see relative_time being useful for a lot of people
Anyway, Iād open a new topic, as helping here in this overcrowded place is kinda difficult (and not the scope of this topic). If you decide to do so, please tag me, so I donāt miss it (hopefully).