python 时间转换(day,hous,minute,second)实例代码

发布时间:2020-12-31编辑:脚本学堂
分享一例python代码,学习下python时间转换的方法,包括day,hous,minute,second等的转换。有需要的朋友参考下。

python实现时间转换的例子。
代码:
 

复制代码 代码示例:
#!/bin/python
#coding=utf-8
import os
import linecache
class convert_time(object):
      
    def __init__(self,user,start,end):
         
        self.user = user
        self.start = start
        self.end = end
    def date_comm(self):
        
        comm = "yhacct -u {0}  -S {1} -E {2} -o CPUTime |  grep -v  '  00:00:00' | sed 's/^  /0-/g' |grep -vE '^0- CPUTime|----------' > {3}.log".format(self.user,self.start,self.end,self.user)
        os.system(comm)
        file_time = [ x for x in linecache.getlines('%s.log' % user) ]
        return file_time
    #python时间转换之日期
    def date_convert(self):
        'Get the user time, generate a dictionary'
        #datestr = ['13-10:33:22','11-12:14:12','23-01:03:12']
        datestr = self.date_comm()
        time_list = { 'days':0,'hours':0,'minute':0,'second':0 }
        for x in xrange(len(datestr)):
            time = datestr[x].split('-')
            time_l = time[1].split(':')
            time_list['days']   += float(time[0])
            time_list['hours']  += float(time_l[0])
            time_list['minute'] += float(time_l[1])
            time_list['second'] += float(time_l[2])
      
        return time_list
    #python时间转换之小时
    def convert_hours(self):
        'Converts time into hours'
        time_all  = self.date_convert()
        hours_total = time_all['days'] * 24 + time_all['hours'] + round(time_all['minute'] / 60) + round(time_all['second'] / 120)
      
        return hours_total
    #python时间转换之分钟
    def convert_minute(self):
        'Converts time into minutes'
        time_all  = self.date_convert()
        min_total = time_all['days'] * 24 * 60 + time_all['hours'] * 60 + time_all['minute']  + round(time_all['second'] / 60)
      
        return min_total
    #python时间转换之秒数
    def convert_second(self):
        'Converts time into second'
        time_all  = self.date_convert()
        sec_total = time_all['days'] * 24 * 120 + time_all['hours'] * 120 + time_all['minute']  + time_all['second']
      
        return sec_total
if __name__ == '__main__':
     
    user =  raw_input('请输入想查询的用户名:')
    start = raw_input('请输入开始时间(格式:2012-03-10): ')
    end  = raw_input('请输入结束时间(格式:2012-04-10): ')
      
    ct =  convert_time(user,start,end)
    print ct.date_convert()
    print """
         -------------- {3}用户使用机时如下:---------------------
                   
                         总计:{0}小时
                               {1}分钟
                               {2}秒
        --------------------------------------------------------
    """.format(ct.convert_hours(),ct.convert_minute(),ct.convert_second(),user)