2016-10-02 125 views
-1

我最近开始研究Python程序,如下面的片段所示。Python和时间/日期时间

# General Variables 
running = False 
new = True 
timeStart = 0.0 
timeElapsed = 0.0 

def endProg(): 
    curses.nocbreak() 
    stdscr.keypad(False) 
    curses.echo() 
    curses.endwin() 
    quit() 

# Draw 
def draw(): 
    stdscr.addstr(1, 1, ">", curses.color_pair(6)) 
    stdscr.border() 
    if running: 
     stdscr.addstr(1, 3, t.strftime("%H:%M.%S", t.ctime(timeStart - timeElapsed))) 

     stdscr.redrawwin() 
    stdscr.refresh() 

# Calculate 
def calc(): 
    if running: 
     timeElapsed = t.clock() - timeStart 

stdscr.border() 
stdscr.addstr(1, 3, t.strftime("%H:%M.%S", t.gmtime(t.clock() - t.clock()))) 

# Main Loop 
while True: 
    # Get Input 
    kInput = stdscr.getch() 

    # Close the program 
    if kInput == ord('q'): 
     endProg() 

    # Stop the current run 
    elif kInput == ord('s'): 
     stdscr.addstr(1, 3, t.strftime("%H:%M.%S", t.gmtime(t.clock() - t.clock()))) 
     running = False 
     new = True 

    # Start a run 
    elif kInput == ord(' ') and new: 
     running = not running 
     new = not new 
     timeStart = dt.datetime.now() 

    # Toggle the timer 
    elif kInput == ord('p') and not new: 
     timeStart = dt.datetime.now() - timeStart 
     running = not running 

    calc() 
    draw() 

我的计划是解决目前,对不起之间的位,如果事情看起来不正确。我会很乐意解释。

我已经花了最近几个小时在网上阅读关于Python的时间和日期时间模块,试图找出我如何使用它们来实现我的目标,但是,但我试图实现它们一直没有用。

本质上,我需要我的程序来衡量从一个按钮被按下并能够以小时显示它的经过时间:minute.second格式。减法使它变得非常困难,不得不实现诸如timedelta之类的东西。从我在线阅读的内容来看,如果没有日期时间模块,没有办法做到我想要的东西,但它只给我提供了一些问题。

有没有更简单的解决方案,我的代码是否有任何突出的错误,我有多愚蠢?

+0

您可以使用'time.time'来测量已用时间。 –

回答

0

使用'time.time`:

import time 

star = time.time() 
# run long processing... 
elapsed = time.time() - start 

的Et瞧!

0
def draw(): 
    stdscr.border() 
    if running: 
     stdscr.addstr(1, 1, ">", curses.color_pair(8)) 
     stdscr.addstr(1, 3, t.strftime("%H:%M.%S", t.gmtime(timeElapsed))) 

    if not running: 
     stdscr.addstr(1, 1, ">", curses.color_pair(7)) 

    stdscr.redrawwin() 
    stdscr.refresh() 

# Calculate 
def calc(): 
    if running: 
     timeElapsed = t.time() - timeStart 

stdscr.border() 
stdscr.addstr(1, 3, t.strftime("%H:%M.%S", t.gmtime(t.time() - t.time()))) 

# Main Loop 
while True: 
    # Get Input 
    kInput = stdscr.getch() 

    # Close the program 
    if kInput == ord('q'): 
     endProg() 

    # Stop the current run 
    elif kInput == ord('s'): 
     running = False 
     new = True 

    # Start a run 
    elif kInput == ord(' ') and new: 
     running = not running 
     new = not new 
     timeStart = t.time() 

    # Toggle the timer 
    elif kInput == ord('p') and not new: 
     running = not running 
     timeStart = t.time() - timeStart 

    calc() 
    draw() 

嗯,我设法摆脱了所有我遇到的错误。但是,显示的时间不正确。

由于我们正在寻找经过的时间,它应该从0开始并增加。我的程序开始于12:21.xx并且正在增加。

看着我的代码,我没有看到任何错误,但显然有一个地方在那里。