time

Pausing the program, timestamps, and precise measurement of code execution time.

On this page

Example

#
Python
import time

for seconds in range(3, 0, -1):
    print(f"Starting in {seconds}...")
    time.sleep(1)

print("Go!")
Resultsaved result, you can check it
Starting in 3...
Starting in 2...
Starting in 1...
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

#
Syntax
import time

time.sleep(seconds)
time.time()
time.perf_counter()
time.strftime(format, struct_time)

More examples

#
Measuring execution time
Python
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")
Result
Click Run to see the result.

The first line is always 333332833333500000. The measured time depends on the computer, e.g. The calculation took 0.041 s.

A timestamp converted to a date
Python
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))
Resultsaved result, you can check it
2026 9 21
2026-09-21 14:13:20

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 the timeit module.
  • In asynchronous programs, do not use time.sleep(), because it blocks the whole event loop. Write await asyncio.sleep() instead.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.