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.
This is great! Your function should be implemented in
datetime
, for real!Based on your code, I created a similar function for the
timedelta
object fromdatatime
. Here it is, along with a simple example: https://gist.github.com/mikbuch/6678247656cd8eee6b70af9486db3f20