Python进阶-时间模块

发布于 2022-01-24  692 次阅读


对time包的使用

主要内容包含time.time(), time.sleep(),及 datetime模块等内容

import time

def calcProd():
    # Calculate the product of the first 100000 numbers.
    product = 1
    for i in range(1, 100000):
        product = product * i
    return product


startTime = time.time()  # 生成时间戳
prod = calcProd()
endTime = time.time()
print('The result is %s digits long.' % (len(str(prod))))
print('Took %s seconds to calculate.' % (endTime - startTime))


import time

time.sleep(30)
# 上面调用用来暂停30秒,注意,此时按下Ctrl-C不会中断sleep()调用,程序会等待暂停结束,再抛出KeyboardInterrupt异常。
# 要绕过这个问题,要用如下的30次循环调用来解决。
for i in range(30):
    time.sleep(1)

每一次按下回车后显示当前一轮的时间,及累积时间、

例子:秒表

import time
# Display the program's instructions.
print('Press ENTER to begin. Afterwards,press ENTER to "click" the stopwatch.Press Ctrl-C to quit.')
input()                      # Press Enter to begin
print('Started.')
startTime = time.time()      # Get the first lap's start time
lastTime = startTime
lapNum = 1
# Start tracking the lap times.
try:
    while True:
        input()
        lapTime = round(time.time() - lastTime, 2)
        totalTime = round(time.time() - startTime, 2)
        print('Lap #%s: %s (%s)' % (lapNum,totalTime,lapTime),end='')
        # 由于前面有个input(),这里向print()函数传入 end='' ,避免输出重复空行
        lapNum += 1
        lastTime = time.time()    # reset the last lap time
except KeyboardInterrupt:
    # Handle the Ctrl-C exception to keep its error message from displaying.
    print('\nDone.')


不要害怕告别,要相信,四季更替,花开花落,都是命中注定。