为了美化日志输出程序执行的总时间,同时人们能够快速获取所需要的信息,需要把输出的秒数转换成  228 days, 22 hour, 9 min,39.0 sec 这样的格式。
因为考虑到判断的重复型,这个函数运用递归的思维方式编写的。

代码 复制 - 运行

#coding:utf8  
import time  
import math  
          
def changeTime(allTime):  
    day = 24*60*60  
    hour = 60*60  
    min = 60  
    if allTime <60:          
        return  "%d sec"%math.ceil(allTime)  
    elif  allTime > day:  
        days = divmod(allTime,day)   
        return "%d days, %s"%(int(days[0]),changeTime(days[1]))  
    elif allTime > hour:  
        hours = divmod(allTime,hour)  
        return '%d hours, %s'%(int(hours[0]),changeTime(hours[1]))  
    else:  
        mins = divmod(allTime,min)  
        return "%d mins, %d sec"%(int(mins[0]),math.ceil(mins[1]))  
  
  
  
  
if __name__=="__main__":  
    nums = 19778979  
    t = time.time()  
    data = changeTime(nums)  
    print time.time() -t  
    print data  



代码 复制 - 运行

irsadmin@IR-ZHANGCHENG ~/Desktop/iOpenData   
$ python dataGenerat.py  
0.0  
3 min,18.0 sec  
  
  
irsadmin@IR-ZHANGCHENG ~/Desktop/iOpenData   
$ python dataGenerat.py  
0.0  
228 days, 22 hour, 9 min,39.0 sec  
  
  
irsadmin@IR-ZHANGCHENG ~/Desktop/iOpenData   
$  

http://blog.csdn.net/u010808961/article/details/38588071