How to display how much time has passed since a button is pressed

Hi everyone!

I’m stuck on something that should be simple: I would like to create a button which, when pressed, displays a timer that counts from 0 and up until the button is pressed again.
As a bonus, I would like the button to display “Start” when not pressed, and then change the label of the same button to “End” when the button is pressed.

Thanks! :herb:

Hi @ettorecarlessi,

Thanks for posting!

You can use Python’s time module to display how many seconds have passed since the button was pressed.

Here’s an example (and you can just use st.button instead of pressing enter):

import time

def time_convert(sec):

mins = sec // 60

sec = sec % 60

hours = mins // 60

mins = mins % 60

print("Time Lapsed = {0}:{1}:{2}".format(int(hours),int(mins),sec))

input("Press Enter to start")

start_time = time.time()

input("Press Enter to stop")

end_time = time.time()

time_lapsed = end_time - start_time

time_convert(time_lapsed)

Caroline :balloon:

1 Like

Hey @Caroline ! Thanks for your answer.

Unfortunately this method does not work, I’d already tried it but:

  1. I need a clock that displays the time passing by.
  2. I need a solution that prevents the website to “pause” while executing the function, because when the user presses the button, besides starting the timer, multiple functions have to execute.

I found this solution with asyncio but unfortunately I can’t seem to make it work for my needs.

Hi @ettorecarlessi,

You can create a clock that displays the passed time by just subtracting the start time from the current time and updating it every second (i.e. use time.sleep(1) to pause for 1 second). If you put all of that in a “while True” loop, it would run continuously – I’m not aware of a better way to get it to run continuously unfortunately.

Caroline

I found a way to make the clock work as intended, for posterity:

async def time_convert():
    container = st.empty()
    container_2 = st.empty()
    button_start = container_2.button('Start')
    clock = f"{0:02d}:{0:02d}"
    if button_start:
        while True:
            button_end = container_2.button('End')
            for secs in range(0, 1000, 1):
                mm, ss = secs // 60, secs % 60
                container.metric("Time Lapsed", f"{mm:02d}:{ss:02d}")
                r = await asyncio.sleep(1)
            if button_end:
                container_2.empty()
                button_start = container_2.button('Start')
                break
    else:
        container.metric("Time Lapsed", clock)

Now the only problem is that when this function executes I can’t execute other things on the website. The asyncio trick should work but it doesn’t. Someone knows how to solve this issue?