Posted By

wbowers on 04/05/08

Statistics

Viewed 1220 times
Favorited by 2 user(s)

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.

Copy this code and paste it in your HTML
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, 60 * 60 * 24 * 7 * 52),
12. (suffixes, 60 * 60 * 24 * 7),
13. (suffixes, 60 * 60 * 24),
14. (suffixes, 60 * 60),
15. (suffixes, 60),
16. (suffixes, 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=', ') Subscribe to comments