We Recommend

Learning Python Learning Python
The authors of Learning Python show you enough essentials of the Python scripting language to enable you to begin solving problems right away, then reveal more powerful aspects of the language one at a time. This approach is sure to appeal to programmers and system administrators who have urgent problems and a preference for learning by semi-guided experimentation.


Posted By

wbowers on 04/05/08


Tagged

time human readable python function seconds elapsedtime


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

wbowers
taboularasa


Python: elapsed_time (human readable time span given total seconds)


Published in: Python 


This function takes an amount of time in seconds and returns a human readable time span (i.e., 4h 5m 23s). The suffixes (d for day, h for hour) are configurable to whatever you want (like day, hour, week, etc). Read the comments within the code for more detail.

  1. def elapsed_time(seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=' '):
  2. """
  3. Takes an amount of seconds and turns it into a human-readable amount of time.
  4. """
  5. # the formatted time string to be returned
  6. time = []
  7.  
  8. # the pieces of time to iterate over (days, hours, minutes, etc)
  9. # - the first piece in each tuple is the suffix (d, h, w)
  10. # - the second piece is the length in seconds (a day is 60s * 60m * 24h)
  11. parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52),
  12. (suffixes[1], 60 * 60 * 24 * 7),
  13. (suffixes[2], 60 * 60 * 24),
  14. (suffixes[3], 60 * 60),
  15. (suffixes[4], 60),
  16. (suffixes[5], 1)]
  17.  
  18. # for each time piece, grab the value and remaining seconds, and add it to
  19. # the time string
  20. for suffix, length in parts:
  21. value = seconds / length
  22. if value > 0:
  23. seconds = seconds % length
  24. time.append('%s%s' % (str(value),
  25. (suffix, (suffix, suffix + 's')[value > 1])[add_s]))
  26. if seconds < 1:
  27. break
  28.  
  29. return separator.join(time)
  30.  
  31. if __name__ == '__main__':
  32. # 2 years, 1 week, 6 days, 2 hours, 59 minutes, 23 seconds
  33. # 2y 1w 6d 2h 59m 23s
  34. seconds = (60 * 60 * 24 * 7 * 52 * 2) + (60 * 60 * 24 * 7 * 1) + (60 * 60 * 24 * 6) + (60 * 60 * 2) + (60 * 59) + (1 * 23)
  35. print elapsed_time(seconds)
  36. print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'])
  37. print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'], add_s=True)
  38. print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'], add_s=True, separator=', ')

Report this snippet 

You need to login to post a comment.