Phiplex - 7 months ago 61

Python Question

Is there a simple way in Python to format a time (delta) as follows:

`10:11:12 -> 10:11:12`

09:10:11 -> 9:10:11

00:10:11 -> 10:11

00:09:10 -> 9:10

00:00:10 -> 10 (or maybe as 0:10)

00:00:09 -> 9 (or maybe as 0:09)

I.e. suppressing leading zeros and separators

(but maybe not when time delta is < 1 minute)

Answer

If you have the string, you could just *lstrip* any leading colons or 0's:

```
In [3]: "00:00:10".lstrip("0:")
Out[3]: '10'
In [4]: "09:10:11".lstrip("0:")
Out[4]: '9:10:11'
In [5]: "10:10:11".lstrip("0:")
Out[5]: '10:10:11'
```

It is only gong to strip as long as we have a 0 or : and stop as soon as we find anything other than the two chars. One case you might want to catch is `"00:00:00"`

. In that situation I have no idea what you expect.

If you are trying to also right align, you can *rjust* the result:

```
In [18]: "00:00:19".lstrip("0:").rjust(8)
Out[18]: ' 19'
In [19]: "10:00:19".lstrip("0:").rjust(8)
Out[19]: '10:00:19'
In [20]: "09:00:19".lstrip("0:").rjust(8)
Out[20]: ' 9:00:19'
```

Of use *str.format* as @C.LECLERC commented.

```
"{:>8}".format("00:10:11".lstrip("0:"))
```