Python 和小时公式计算

3 投票
4 回答
1102 浏览
提问于 2025-04-17 07:00

我有一些可以正常运行的代码,但我对小时这个变量的计算总是搞不对。我觉得可能是节假日吃得太多了,现在脑子一片空白。

## {{{ http://code.activestate.com/recipes/124894/ (r2)
from Tkinter import *
import time
import pygtk
import gtk
import time

class StopWatch(Frame):  
    """ Implements a stop watch frame widget. """                                                                
    def __init__(self, parent=None, **kw):        
        Frame.__init__(self, parent, kw)
        self._start = 0.0        
        self._elapsedtime = 0.0
        self._running = 0
        self.timestr = StringVar()               
        self.makeWidgets()      

    def makeWidgets(self):                         
        """ Make the time label. """
        l = Label(self, textvariable=self.timestr)
        self._setTime(self._elapsedtime)
        l.pack(fill=X, expand=NO, pady=2, padx=2)                      

    def _update(self): 
        """ Update the label with elapsed time. """
        self._elapsedtime = time.time() - self._start
        self._setTime(self._elapsedtime)
        self._timer = self.after(50, self._update)

    def _setTime(self, elap):
        """ Set the time string to Minutes:Seconds:Hundreths """
        hours = int(elap) #cant remember formula 
        minutes = int(elap/60)
        seconds = int(elap - minutes*60.0)
        hseconds = int((elap - minutes*60.0 - seconds)*100)
        sn = time.strftime('%m/%d/%Y-%H:%M:%S')                
        self.timestr.set('%02s\n\n%02dh:%02dm:%02ds:%02d' % (sn,hours,minutes, seconds, hseconds))

    def Start(self):                                                     
        """ Start the stopwatch, ignore if running. """
        if not self._running:            
            self._start = time.time() - self._elapsedtime
            self._update()
            self._running = 1        

    def Stop(self):                                    
        """ Stop the stopwatch, ignore if stopped. """
        if self._running:
            self.after_cancel(self._timer)            
            self._elapsedtime = time.time() - self._start    
            self._setTime(self._elapsedtime)
            self._running = 0

    def Reset(self):                                  
        """ Reset the stopwatch. """
        self._start = time.time()         
        self._elapsedtime = 0.0    
        self._setTime(self._elapsedtime)



def main():
    root = Tk()
    root.title( "Stop Watch" )
    sw = StopWatch(root)
    sw.pack(side=TOP)

    Button(root, text='Start', command=sw.Start).pack(side=LEFT)
    Button(root, text='Stop', command=sw.Stop).pack(side=LEFT)
    Button(root, text='Reset', command=sw.Reset).pack(side=LEFT)
    Button(root, text='Quit', command=root.quit).pack(side=LEFT)

    root.mainloop()

if __name__ == '__main__':
    main()
## end of http://code.activestate.com/recipes/124894/ }}}

4 个回答

0

现在无法测试,但根据代码来看,elap表示经过的秒数。所以你需要把它除以3600,这样就能得到小时数,而用int()函数会把结果向下取整。这意味着在之前的代码中,可能会显示90分钟,但现在应该显示为1小时30分钟。因此,除了计算小时数,你还需要相应地调整minutes(分钟)、seconds(秒)和hseconds(毫秒)。

def _setTime(self, elap):
    """ Set the time string to Hours:Minutes:Seconds:Hundreths """
    hours = int(elap/3600)
    minutes = int(elap/60 - hours*60.0)
    seconds = int(elap - hours*3600.0 - minutes*60.0)
    hseconds = int((elap - hours*3600.0 - minutes*60.0 - seconds)*100)
    sn = time.strftime('%m/%d/%Y-%H:%M:%S')                
    self.timestr.set('%02s\n\n%02dh:%02dm:%02ds:%02d' % (sn,hours,minutes, seconds, hseconds))
5

从另一个角度入手会简单很多。你不需要像 86400 这样的大数字,这样会让审查代码的人不得不拿出计算器来算。

c = int(elap * 100) # centiseconds
s, c = divmod(c, 100)
m, s = divmod(s, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
print(d, h, m, s, c)

或者,避免使用函数调用:

c = int(elap * 100) # centiseconds
s = c // 100; c %= 100
m = s //  60; s %=  60
h = m //  60; m %=  60
d = h //  24; h %=  24
print(d, h, m, s, c)
2

从这些公式来看,elap 是用秒来计算的。因为你把小时单独提取成一个变量,所以需要把这些小时从分钟的总数中去掉。当然,在后面的计算中也要保持一致,因为这时候minutes的意思和原来的代码不一样了。

hours = int(elap/3600)
minutes = int((elap-hours*3600)/60)
seconds = int(elap-hours*3600-minutes*60)
hseconds = int((elap-hours*3600-minutes*60-seconds)*100)

我觉得如果是我在写这个代码,我会在进行的过程中修改elap,这样可以减少重复的部分。

hours = int(elap/3600)
elap -= hours*3600
minutes = int(elap/60)
elap -= minutes*60
seconds = int(elap)
elap -= seconds
hseconds = int(elap*100)

这样做会让你更容易理解代码的运行情况,也更方便以后进行修改。比如说,如果你想要加入天数,只需要在代码的开头加上这一部分:

days = int(elap/86400)
elap -= days*86400

现在,我在这里写的代码假设elap是一个float类型,当然在你的程序里也是这样。如果你特别谨慎的话,可以在进行数学运算之前写elap = float(elap)

不过我同意@soulcheck的看法,使用库函数会让代码看起来更整洁。

撰写回答