timedelta = [("d", 24*3600), ("h", 3600), ("m", 60), ("s", 1)] def duration_to_string(duration: float) -> str: """ Convert a duration in seconds to a string of the form "d h m s" where only the largest units are included. Parameters ---------- duration: float Duration in seconds. Returns ------- String representation of the duration. """ include = False s = "" sign = 1 if duration > 0 else -1 time_left = abs(int(duration)) for i, (unit, unit_seconds) in enumerate(timedelta): t = int(time_left / unit_seconds) if t != 0 or include or unit == "s": s += f"{sign*t:02}{unit} " include = True time_left %= unit_seconds return s.strip()