Python basic time module (making stopwatch and countdown)

time module

Using Python to complete automated tasks often requires running or scheduling based on specific times and dates. The built-in time module in Python can be used to read the current time of the system clock. The most commonly used time modules are time.time() and time.sleep().

1, Get current time

time.time() function

Returns the number of seconds since 0:00 on January 1, 1970, known as the UNIX era timestamp. Note: Not readable by humans.

import time
time.time()
# output
1653451585.033248

time.ctime() function

Returns a string description of the current time for easy reading. It is also possible to return the string description of the timestamp by passing in a timestamp parameter.

time.ctime()
# output 
'Wed May 25 14:57:11 2022'
time.ctime(1653451585.033248)
# output
'Wed May 25 12:06:25 2022'

Application 1: Calculating the Time of a Program

import time
def task():
out = 1
for i in range(1,100000000):
  out = out + i
return out
startTime = time.time()
out = task()
endTime = time.time()
print(f"add up to 100 million results :{out}")
print(f"implement task () function time :{endTime - startTime}")
# output
 add up to 100 million results :4999999950000001
 implement task () function time :3.8387675285339355

Application 2: Stop Watch

import time
#stop watch mini program 
print("welcome to the stopwatch mini program. press enter to start timing, and press enter again to record the current time. according to [ctrl+c] end stopwatch")
input()
print("stop watch start")
#initialization 
startTime = time.time()
lastTime = startTime
num = 1
try:   
while True:
  input()
  deltaTime = round(time.time() - lastTime, 2)
  totalTime = round(time.time() - startTime, 2)
  print('sign %dt+%st%s' %(num,deltaTime,totalTime))
  num += 1
  lastTime  = time.time()   #the start time of the last lap 
except KeyboardInterrupt:
#press on the command line [ctrl+c] will throw KeyboardInterrupt abnormal 
print("timing ended")

2, Pause the program

time.sleep() function

time.sheep(5) #pause for 5 seconds 

Application 3: Countdown

import time
#countdown mini program 
totalTime = input("please enter the number of seconds for the countdown :")
if totalTime.isdigit():
print(totalTime)
totalTime = int(totalTime)
while totalTime>0:
  print('remaining %d second'% totalTime)
  time.sleep(1)
  totalTime-=1
print("time is up")
else:
print("please enter an integer")