Python:elapsedu time(给定总秒数的人类可读时间跨度)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python:elapsedu time(给定总秒数的人类可读时间跨度)相关的知识,希望对你有一定的参考价值。

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=', ')

以上是关于Python:elapsedu time(给定总秒数的人类可读时间跨度)的主要内容,如果未能解决你的问题,请参考以下文章

Code-Linux-time_t

python的内置函数time

Python time.time()方法

Shell脚本整理

python(time/random模块)

Python 学习笔记 -- time模块内置函数及实例