I needed to print time deltas in a compact hours, minutes seconds format for log output. As an example try these on the Python console:
>>> pretty_time_delta(123)
'2m3s'
>>> pretty_time_delta(12345)
'3h25m45s'
>>> pretty_time_delta(1234567)
'14d6h56m7s'
It only displays to second precision and only displays up to hours as the largest unit. To convert a standard Python datetime.timedelta
, use the total_seconds()
method on your timedelta
to convert to seconds. If all your calls come from standard Python datetime
operations, you probably want to change line 3 to something like:
seconds = abs(int(seconds.total_seconds()))
The built-in string representation of a timedelta
is also quite acceptable for most situations and also handles sub-second precision (see the last example):
>>> import datetime
>>> str(datetime.timedelta(seconds=123))
'0:02:03'
>>> str(datetime.timedelta(seconds=12345))
'3:25:45'
>>> str(datetime.timedelta(seconds=1234567))
'14 days, 6:56:07'
>>> str(datetime.timedelta(seconds=123.456789))
'0:02:03.456789'
The version included in python-pretty-time-delta-positive-only.py
has the negative number handling stripped out for some slightly simpler code.
Stole this to track some machine learning code that's going to take about 5 hours to run. Thanks for publishing it!