Skip to content

Commit 6a5e7e9

Browse files
committed
Don't rely on durationpy for formatting; just do it manually.
This approach is less fragile, and also allows all three implementations (Rust, Go, and Python) to work in a similar way. Signed-off-by: Flynn <[email protected]>
1 parent 1bc5b5e commit 6a5e7e9

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

kubernetes/utils/duration.py

+21-11
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
from typing import List
15+
1416
import datetime
1517
import re
1618

@@ -147,18 +149,26 @@ def format_duration(delta: datetime.timedelta) -> str:
147149
.format(delta)
148150
)
149151

150-
# Second short-circuit.
152+
# After that, do the usual div & mod tree to take seconds and get hours,
153+
# minutes, and seconds from it.
154+
secs = int(delta.total_seconds())
155+
156+
output: List[str] = []
157+
158+
hours = secs // 3600
159+
if hours > 0:
160+
output.append(f"{hours}h")
161+
secs -= hours * 3600
151162

152-
delta -= datetime.timedelta(microseconds=delta_us)
153-
delta_ms = delta_us // 1000
154-
delta_str = durationpy.to_str(delta)
163+
minutes = secs // 60
164+
if minutes > 0:
165+
output.append(f"{minutes}m")
166+
secs -= minutes * 60
155167

156-
if delta_ms > 0:
157-
# We have milliseconds to add back in. Make sure to not have a leading
158-
# "0" if we have no other duration components.
159-
if delta == datetime.timedelta(0):
160-
delta_str = ""
168+
if secs > 0:
169+
output.append(f"{secs}s")
161170

162-
delta_str += f"{delta_ms}ms"
171+
if delta_us > 0:
172+
output.append(f"{delta_us // 1000}ms")
163173

164-
return delta_str
174+
return "".join(output)

0 commit comments

Comments
 (0)