I wanted to write a human readable datetime.timedelta that can be used in log files.
Eg, "Report issued 1 hour, 44 minutes, 20 seconds ago"
I noticed that casting a timedelta to str() generates something almost like what I want, but not quite.
To this end I wrote this:
def verbose_timedelta(delta): hours, remainder = divmod(delta.seconds, 3600) minutes, seconds = divmod(remainder, 60) dstr = "%s day%s" % (delta.days, "s"[delta.days==1:]) hstr = "%s hour%s" % (hours, "s"[hours==1:]) mstr = "%s minute%s" % (minutes, "s"[minutes==1:]) sstr = "%s second%s" % (seconds, "s"[seconds==1:]) dhms = [dstr, hstr, mstr, sstr] for x in range(len(dhms)): if not dhms[x].startswith('0'): dhms = dhms[x:] break dhms.reverse() for x in range(len(dhms)): if not dhms[x].startswith('0'): dhms = dhms[x:] break dhms.reverse() return ', '.join(dhms)
Essentially, it's shaving off both ends of a list to make the results more meaningful.
The code above feels clunky though. Is there a more "Pythonic" way to do it? I'm using Python 2.7.3.