Search code examples
pythondatetimetimedeltastopwatch

Did a stopwatch using time libraries, it worked as expected, but it returns none also


I'm new to python, so I was following a few tutorials to understand how to do something I liked to do. A stopwatch returning not only the time passed but also the time it started and finished. My plan started creating two variables with time.time, one for the start and another for the finish. So I subtracted the final time minus the start, and get time lapsed. Then I added two more variables, one for the time the program stopped counting, and another for the time it started. For the finish time it was easy, just used dateTime.now(), and for the time start I decided timeDelta might be usefull, so I did subtracted current time minus time lapsed, and get time started. It worked as expected as I said in the title, except for a little detail, which is also returning a None value apart of my time lapsed, so I'm not quite sure why being new to Python and being all I know from tutorials that don't explained these things. If you could give me any sort of explanation it'll help a lot!

import time
from datetime import datetime, timedelta

time_ended=datetime.now()

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_started=timedelta(((time_lapsed/24)/60)/60)

print("Time started: ",time_ended-time_started)
print(time_convert(time_lapsed))
print("Time finished: ",time_ended)

This is what happen after running the program

Press Enter to start

Press Enter to stop

Time started: 2022-06-08 14:01:20.396229

Time Lapsed = 0:0:53.04069781303406

None

Time finished: 2022-06-08 14:02:13.436927

BTW, I did try to delete the first "import time" but it brokes my code, and trying to do something like putting at the end of the second line a ",time" deleting the first line again, it doesn't work neither.


Solution

  • print(time_convert(time_lapsed))

    Is your problem. The tine_convert method doesn't return anything. So by encapsulating the function in a print function it just prints none.

    Try returning a string in the end of your method like: Return "test"