time
Pausing the program, timestamps, and precise measurement of code execution time.
Example
#import time
for seconds in range(3, 0, -1):
print(f"Starting in {seconds}...")
time.sleep(1)
print("Go!")The lines appear one second apart.
Definition and usage
#The time module provides basic time-related functions. time.sleep(seconds) pauses the program for the given time, time.time() returns the number of seconds that have passed since January 1, 1970 (the so-called Unix timestamp), and time.perf_counter() is for precisely measuring how long a piece of code took.
For measurements, choose perf_counter(), not time(). The system clock can be adjusted, for example during synchronization with the internet, while perf_counter() only ever goes up and has high precision. Only the difference between two readings matters.
The functions gmtime(), localtime(), and strftime() convert a timestamp into a date and text. For calculations on dates, such as adding days or comparing deadlines, the datetime module is more convenient.
Syntax
#import time
time.sleep(seconds)
time.time()
time.perf_counter()
time.strftime(format, struct_time)More examples
#import time
start = time.perf_counter()
total = sum(n * n for n in range(1_000_000))
elapsed = time.perf_counter() - start
print(total)
print(f"The calculation took {elapsed:.3f} s")The first line is always 333332833333500000. The measured time depends on the computer, e.g. The calculation took 0.041 s.
import time
moment = time.gmtime(1_790_000_000)
print(moment.tm_year, moment.tm_mon, moment.tm_mday)
print(time.strftime("%Y-%m-%d %H:%M:%S", moment))gmtime() gives UTC time. Local time is returned by localtime(), and the current timestamp by time.time().
Good practices
#- Measure code execution time with
time.perf_counter(). For comparing the performance of short snippets there is also thetimeitmodule. - In asynchronous programs, do not use
time.sleep(), because it blocks the whole event loop. Writeawait asyncio.sleep()instead.
Related entries
#- datetimeDates and times: creating, formatting, parsing from text, and calculations on time intervals.
- async and awaitAsynchronous programming: waiting for operations without blocking the whole program.
- randomRandom numbers and items: rolling a die, picking from a list, shuffling, and random samples.
- sysAccess to the interpreter: command-line arguments, ending the program, the Python version, and streams.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.