Time interval to string

Dear all,
I wonder if there is a built in function/filter I coud use to display intervals (received via MQTT as a decimal, like 1234.56) to a string, like 20 min 34.56 s.
Any pointers would be appreciated!

Well, I figured it. In case someone is interested, here it is:

{{ timedelta (seconds = states("sensor.custom_print_time_left") | int ) }}

Your solution gives a representation: if you’re happy with that, fine :slight_smile: . For more precise control of formatting, like

you might need to get a bit more involved.:

{% set s = 1234.56 %}

{{ timedelta(seconds=s) }}

{{ [(s//3600)|int ~ ' hr' if s//3600 else '',
    (s%3600//60)|int ~ ' min' if s%3600//60 else '',
    (s%60)|round(2) ~ ' s' if s%60 else '']
   |select('ne','')|join(' ') }}

image

1 Like

Yes, thank you for your input!

I indeed just needed the representation, I wasn’t clear about it in my question.
I can see your algorithm - nothing fancy in it, I would have done the same. Just wanted to know if there is a built in way of doing it. Apparently not. :slight_smile:

Thanks again for your quick reply!!!

{{ states('sensor.custom_print_time_left') | timestamp_custom('%-M min %-S sec', false) }}

If you foresee it can exceed an hour, use %-H hr %-M min %-S sec

Need to be aware of overflow limits though:

image

Yepp, that IS a limit for me. The one I found timedelta works correctly for larger intervals as well.

1 Like

It’s certainly more compact, particularly if you need days also!

How large are the “larger intervals”?

If it’s less than 24 hours, what I suggested will report the correct time (provided you include %H as mentioned).

It’s undeniably compact, as long as one accepts the reported data’s format because there’s no control over it.

Viktak’s first post appeared to request a desired format:

like 20 min 34.56 s

But it seems viktak dropped that requirement and has accepted whatever format is produced by timedelta … then changed his mind and reinstated the need for the original format.

Ah yes, I didn’t even notice… :slight_smile: Since it displays a 3D printer’s remaining time, I don’t really care about the decimals… With my suggestion now it reports the time remaining correctly:

image

Anyway, that’s why I like the forums, because even if I figure something out, there may be a better way of doing it. I never stop learning! :slight_smile:

1 Like

In case anyone else is looking for a concise way of displaying seconds as hours/minutes/seconds (and suppressing hours or minutes if they’re zero):

{{ states('sensor.custom_print_time_left') | int(0)
  | timestamp_custom('%-H hr %-M min %-S sec', false)
  | regex_replace('(^0 hr| 0 min)', '') | trim }}

The pattern within timestamp_custom is easy to change if you need a different time format.

Reference: strftime


EDIT

I had a sense of déja vu while writing this post and then found that I had suggested the same technique to someone else last month:

2 Likes