# 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 . 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(' ') }}
``````

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.

``````{{ 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:

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â€¦ 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:

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!

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