from __future__ import division from __future__ import print_function from __future__ import with_statement import datetime def time2human(time, digits = 2, cut = True, extended = False, strip = True): """Convert time in seconds in readable format. Specify number of total *digits* and whether to *cut* trailing zeros. If "extended" is set to True, also the numeric value, the unit string and the scale factor are returned. """ import physconst if isinstance(time,datetime.timedelta): time = time.total_seconds() atime = abs(time) xtime = atime su = 's' # big numbers if atime > 99.49999: xtime /= 60 su = 'min' if atime > 60 * 59.49999: xtime /= 60 su = 'h' if atime > 24 * 60 * 99.49999: xtime /= 24 su = 'd' if atime > physconst.SEC: xtime = atime / physconst.SEC su='yr' if atime > physconst.SEC * 999.49999: xtime /= 1000 su='kyr' if atime > physconst.SEC * 999.49999e3: xtime /= 1000 su='Myr' if atime > physconst.SEC * 999.49999e6: xtime /= 1000 su='Gyr' # small numbers ... if atime < 0.99949999: xtime *= 1000 su='ms' if atime < 0.99949999e-3: xtime *= 1000 su='\mu s' if atime < 0.99949999e-6: xtime *= 1000 su='ns' if atime < 0.99949999e-9: xtime *= 1000 su='ps' if atime < 0.99949999e-12: xtime *= 1000 su='fs' if atime < 0.99949999e-15: xtime *= 1000 su='as' sv = "{:20.15f}".format(xtime).strip() i = sv.find('.') l = max(digits + 1, i + 1) format = "{:" + "{:d}".format(l).strip() + "." + "{:d}".format(l-i-1).strip() + "f}" sv = format.format(xtime).strip() if cut: if sv.find('.') > 0: sv = sv.rstrip('0') sv = sv.rstrip('.') if time < 0: sv = '-' + sv s = sv + ' ' + su if strip: s = s.strip() if extended: if xtime == 0: scale = 1 else: scale = atime/xtime numeric = time/scale # if sv.find('.') == -1: # numeric = int(numeric) return s, numeric, su, scale else: return s