2016-10-02 95 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並且正在增加。

看着我的代碼,我沒有看到任何錯誤,但顯然有一個地方在那裏。