MCPcopy Create free account
hub / github.com/apify/crawlee-python / format_duration

Function format_duration

src/crawlee/_utils/time.py:78–120  ·  view source on GitHub ↗

Format a timedelta into a human-readable string with appropriate units.

(duration: timedelta | None)

Source from the content-addressed store, hash-verified

76
77
78def format_duration(duration: timedelta | None) -> str:
79 """Format a timedelta into a human-readable string with appropriate units."""
80 if duration is None:
81 return 'None'
82
83 total_seconds = duration.total_seconds()
84
85 if total_seconds == 0:
86 return '0s'
87
88 # For very small durations, show in milliseconds
89 if total_seconds < 1:
90 milliseconds = total_seconds * 1000
91 if milliseconds < 1:
92 microseconds = total_seconds * 1_000_000
93 return f'{microseconds:.1f}μs'
94 return f'{milliseconds:.1f}ms'
95
96 # For durations less than 60 seconds, show in seconds
97 if total_seconds < _SECONDS_PER_MINUTE:
98 return f'{total_seconds:.2f}s'
99
100 # For durations less than 1 hour, show in minutes and seconds
101 if total_seconds < _SECONDS_PER_HOUR:
102 minutes = int(total_seconds // _SECONDS_PER_MINUTE)
103 seconds = total_seconds % _SECONDS_PER_MINUTE
104 if seconds == 0:
105 return f'{minutes}min'
106 return f'{minutes}min {seconds:.1f}s'
107
108 # For longer durations, show in hours, minutes, and seconds
109 hours = int(total_seconds // _SECONDS_PER_HOUR)
110 remaining_seconds = total_seconds % _SECONDS_PER_HOUR
111 minutes = int(remaining_seconds // _SECONDS_PER_MINUTE)
112 seconds = remaining_seconds % _SECONDS_PER_MINUTE
113
114 result = f'{hours}h'
115 if minutes > 0 or seconds > 0:
116 result += f' {minutes}min'
117 if seconds > 0:
118 result += f' {seconds:.1f}s'
119
120 return result

Callers 2

to_tableMethod · 0.90
test_format_durationFunction · 0.90

Calls

no outgoing calls

Tested by 1

test_format_durationFunction · 0.72