android 创建倒计时计时器

cqoc49vn  于 2023-02-14  发布在  Android
关注(0)|答案(1)|浏览(202)

你能给我做一个包括分/秒/毫秒的倒计时器吗?
这是当前代码,只有分钟/秒

import time

def countdown(time_sec):
    while time_sec:
        mins, secs = divmod(time_sec, 60)

        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        print(timeformat, end='\r')
        time.sleep(1)
        time_sec -= 1
    print("stop")

countdown(180)
hs1ihplo

hs1ihplo1#

如果我们想要毫秒级的精确度,我们需要先将经过的秒数乘以1000,得到毫秒数,然后重复divmod计算,得到当前时间的分、秒和毫秒数,并减少睡眠时间(在Windows中,非常短的睡眠调用不是很精确,所以这可能无法按预期工作):

import time

def countdown(time_sec):

    time_msec = time_sec*1000 # Turn received seconds into milliseconds
    
    while time_msec:
        
        mins, secs = divmod(time_msec, 60000) # Number of milliseconds in a minute
        secs, msecs = divmod(secs, 1000) # Number of milliseconds in a second

        timeformat = '{:02d}:{:02d}.{:03d}'.format(mins, secs, msecs) # Added another field to the format

        print(timeformat, end='\r')

        time.sleep(1/1000) # Reduced sleep length

        time_msec -= 1

    print("stop")

countdown(180)

现在打印:

02:57.292

相关问题