Format sensor uptime to human readable

I am trying to build my own html-template-card for my AP, emulating its default card:

Default card:

2023-11-06 15 26 02

My card:

2023-11-06 15 26 22

I am a hack, not a coder. I’ve been going through the docs trying to figure out how to convert

2023-11-06T22:00:00+00:00

to the readable output in the default card, to no avail.

The code I’m using is quite trivial:

{{ states('sensor.u6_lr_uptime') }}

Have no access to HA now, cannot test myself - but try using “relative_time“.

What is strange is that the sensor is called “uptime”, in fact it keeps a timestamp.

Not short but my favourite as its quite flexible:

        {%- set time = (as_timestamp(now()) - as_timestamp(states('sensor.uptime'))) | 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

You can change the formatting by {}m, {}h, {}d if you wish. I just like the format of 5d 2h 23m ago

Oh, I could have figured that out on my own. Within about 90 hours of serious study. :rofl:

Works a treat! Thanks for sharing.

2023-11-06 20 07 15

Or use Relative Time Plus

It’s more database friendly, as it doesn’t have to write a new state to the database every second.

I beg your pardon - not getting what do you mean. How is that related to my advise to use relative_time?

it was related to your remark that de device_class is uptime while it is actually a timestamp

My remark about “uptime” was based on a name of the sensor from the 1st post:
sensor.u6_lr_uptime
But it’s value looks like a timestamp.
This was not about a device_class (btw, there is no a “uptime” device class).
My remark was only about “why an Uptime value contains a timestamp, may be it should be called a StartTime”.

I was only trying to explain why it makes sense to use a timestamp instead of an actual uptime in seconds. The actual uptime integration does the same thing

you’re right about the device class, my bad

1 Like

Very useful observation. I will go through all my uptime sensors then…