Programming Languages - Python - python timer

Create a Timer in Python: Step-by-Step Guide

Last Updated on July 17, 2026

Figuring out how to make a timer in Python trips up many beginners because there is no single “timer” command. Instead, you combine a few standard library tools to get the behavior you need. The core building blocks are time.time() for capturing timestamps, time.sleep() for pausing execution, and datetime.timedelta() for formatting durations into something readable.

This tutorial covers the three timer patterns that handle nearly every common use case:

  • A stopwatch that measures elapsed time
  • A countdown timer that runs from a set duration down to zero
  • An execution timer that measures how long a block of code takes to run

One point of confusion worth naming early: time.sleep() pauses your program for a given number of seconds, but it does not measure how much time has passed. Measuring time requires capturing timestamps before and after the thing you want to time, then subtracting. The Python time module gives you both capabilities, but they serve different purposes.

What a timer means in Python

The word “timer” gets used loosely. A search for “create a timer in python” could mean any of three distinct patterns, and the implementation is different for each one.

Stopwatch

A stopwatch counts up from a start time. You record a timestamp when the clock starts, record another when it stops, and subtract to get elapsed time. This is the right pattern for tracking how long a task takes, whether that task is a user activity like a typing test or a background process like a file download.

Countdown timer

A countdown timer starts from a fixed number of seconds and reduces that value to zero. Think exam timers, cooking timers, or any situation where a user needs to see remaining time ticking down. The countdown itself is driven by a loop and time.sleep(), not by measuring timestamps.

Execution timer

An execution timer measures how long a specific block of code takes to run. It follows the same start-subtract-stop logic as a stopwatch, but the purpose is different: quick performance checks during development, not user-facing time tracking. This pattern is essential for comparing implementations or identifying slow code paths.

If you are unsure which pattern you need, ask this: Are you tracking time for a person, counting down to an event, or measuring code speed? The answer determines which approach to use.

The Python modules you need

time

The time module is the main tool for beginner timer scripts. Two functions do most of the work:

  • time.time() returns the current time as a Unix timestamp, a floating-point number representing seconds since January 1, 1970. Calling it twice and subtracting gives you elapsed time.
  • time.sleep(seconds) pauses the program for a specified number of seconds. It controls pacing. It does not measure anything.

That distinction matters. time.time() helps measure. time.sleep() helps pace. They are complementary, but they solve different problems.

datetime

The datetime module includes datetime.timedelta(), which is useful for displaying a duration in hours, minutes, and seconds format. If you pass a number of seconds to timedelta(), it returns a formatted object that prints cleanly. This is helpful in countdowns where raw seconds are hard for users to read.

Which one to start with

Start with the time module. It covers stopwatch logic, countdown pacing, and basic execution timing. Reach for datetime when display formatting matters and you want cleaner output without manual conversion.

Module / FunctionBest forWhat it doesLimitation
time.time()Measuring elapsed timeCaptures current timestampNot the best choice for precise benchmarking
time.sleep()Countdown pacingPauses executionBlocks the script while waiting
datetime.timedelta()Readable displayFormats durationsNot a timer by itself

Build a simple stopwatch in Python

The simplest stopwatch captures a start timestamp, waits for the user to signal a stop, then calculates the difference. This is the most direct answer to how to make a timer in python when you need to track elapsed time.

A few terms to be precise about:

  • Timestamp: a numeric value representing a specific point in time
  • Elapsed time: the difference between the end timestamp and the start timestamp

Here is the minimal version:

import time

input("Press Enter to start the stopwatch...")
start_time = time.time()

input("Press Enter to stop the stopwatch...")
end_time = time.time()

elapsed = end_time - start_time
print(f"Elapsed time: {elapsed:.2f} seconds")

This script uses time.time() to grab the current timestamp at two points, then subtracts. The :.2f formatting rounds the output to two decimal places. That is the entire stopwatch pattern: capture, wait, capture, subtract, display.

Once this logic is clear, you can extend it to handle laps, format the output differently, or wrap it in a function.

Add lap timing

Lap timing builds on the basic stopwatch by adding intermediate checkpoints. Instead of a single start and stop, the timer records each lap while keeping a running total.

The key addition is a second variable that tracks the timestamp of the most recent lap. Each time the user signals a lap, the script calculates both the lap duration (time since the last checkpoint) and the total elapsed time (time since the original start).

import time

print("Lap Timer")
print("Press Enter to start. Then press Enter for each lap.")
print("Type 'stop' and press Enter to finish.\n")

input("Press Enter to start...")
start_time = time.time()
last_lap_time = start_time
lap_count = 0

while True:
    action = input("")
    if action.lower() == "stop":
        break

    lap_count += 1
    current_time = time.time()
    lap_duration = current_time - last_lap_time
    total_elapsed = current_time - start_time
    last_lap_time = current_time

    print(f"Lap {lap_count}: {lap_duration:.2f}s | Total: {total_elapsed:.2f}s")

total = time.time() - start_time
print(f"\nFinal time: {total:.2f} seconds across {lap_count} laps")

Here, last_lap_time tracks the previous checkpoint and start_time tracks the full run. Each lap resets only the checkpoint, not the overall clock. A simple command-line lap timer like this is enough for many scripting and productivity tasks.

Build a countdown timer in Python

A countdown timer follows different logic from a stopwatch. Instead of comparing timestamps, it starts from a fixed number of seconds and reduces that value in a loop until it reaches zero.

The step-by-step flow:

  1. Get the total number of seconds from the user
  2. Enter a loop that runs while time remains
  3. Convert seconds into a readable MM:SS display
  4. Print the current remaining time
  5. Pause for one second with time.sleep(1)
  6. Subtract one from the counter
  7. Print a completion message when the loop ends

time.sleep(1) controls the pacing of the countdown. The countdown itself comes from decrementing the remaining time value on each pass through the loop.

import time

total_seconds = int(input("Enter countdown time in seconds: "))

while total_seconds > 0:
    minutes, seconds = divmod(total_seconds, 60)
    print(f"\r{minutes:02d}:{seconds:02d}", end="")
    time.sleep(1)
    total_seconds -= 1

print("\r00:00")
print("Time's up!")

This script uses divmod() to split the remaining seconds into minutes and seconds for display. The \r carriage return overwrites the previous line in the terminal, creating a clean countdown effect. The end="" argument prevents print() from adding a newline after each update.

The int() conversion on the input keeps things simple. For a production script, you would add validation to handle non-numeric input.

Format the countdown as MM:SS

Raw seconds are harder to read than formatted output. The pattern divmod(total_seconds, 60) is the cleanest way to split a number of seconds into minutes and remainder seconds for display:

minutes, seconds = divmod(total_seconds, 60)
formatted = f"{minutes:02d}:{seconds:02d}"

The :02d format specifier pads each value with a leading zero when needed, so 5 minutes and 3 seconds displays as 05:03 rather than 5:3.

datetime.timedelta() can also format durations, but for beginner countdowns, divmod() is the better first choice. It is explicit, easy to control, and does not require importing another module.

Measure program execution time in Python

Sometimes a timer is not shown on screen. It runs behind the scenes to measure how long a script, loop, or function takes to execute. This pattern is the same start-subtract-stop logic as a stopwatch, but the purpose is benchmarking code rather than tracking user time.

The base pattern:

  1. Capture the start time
  2. Run the code
  3. Capture the end time
  4. Subtract to get execution time
import time

start = time.time()

total = 0
for i in range(1_000_000):
    total += i

end = time.time()
print(f"Execution time: {end - start:.4f} seconds")

This example times a simple loop that sums one million integers. The result tells you how long that operation took on your machine. The same pattern works for timing function calls, file operations, database queries, or any block of code you want to measure.

Execution timers are useful for comparing different implementations. If you have two approaches to the same problem, wrapping each one in a start-end timing block gives you a quick, practical comparison without reaching for more advanced profiling tools.

time.time() vs time.perf_counter()

time.time() works well for simple tutorials and general elapsed-time measurement. For benchmarking short code paths, time.perf_counter() is usually the better option. It uses a higher-resolution clock, which means it can capture smaller differences in execution time more accurately.

The practical recommendation: use time.time() when learning timer basics and building straightforward scripts. Switch to time.perf_counter() when measuring code performance and small time differences matter.

import time

start = time.perf_counter()

total = 0
for i in range(1_000_000):
    total += i

end = time.perf_counter()
print(f"Execution time: {end - start:.6f} seconds")
FunctionBest useStrengthTradeoff
time.time()Simple timers and elapsed-time demosEasy to understandLess precise for benchmarking
time.perf_counter()Performance measurementHigher precisionSlightly less intuitive for beginners

For most beginner timer scripts, the difference is negligible. But when precision matters, time.perf_counter() is the right tool.

Common mistakes when making a timer in Python

A few confusion points come up repeatedly when building timers. Most are easy to fix once identified.

  • Using time.sleep() as if it measures time. It pauses execution for a set duration. It does not tell you how much time has passed. To measure elapsed time, capture timestamps with time.time() before and after the code you want to time.
  • Mixing up stopwatch and countdown logic. A stopwatch compares two timestamps. A countdown reduces a remaining value in a loop. They solve different problems and the code looks different.
  • Forgetting that sleep() blocks the script. While time.sleep() is running, the program cannot do anything else. In a simple script this is fine. In anything more complex, blocking can cause problems.
  • Printing raw seconds only. Users do not want to read “327 seconds remaining.” Use divmod() or datetime.timedelta() to convert seconds into minutes and seconds.
  • Using time.time() for tight benchmarking. For precise performance measurement, time.perf_counter() provides higher resolution. time.time() is fine for general use but less reliable for short operations.
  • Skipping input validation. Countdown scripts that take user input should handle non-numeric values. Wrapping int(input(...)) in a try/except block prevents crashes from bad input.

When to use datetime, timeit, or more advanced timer patterns

The scripts in this tutorial cover the fundamentals. A few tools and patterns become useful as timer needs grow more complex.

Use datetime.timedelta() for cleaner display

When a duration needs to display in hours, minutes, and seconds, timedelta() handles the conversion automatically. Pass in a number of seconds and print the result:

from datetime import timedelta
print(timedelta(seconds=3661))

This outputs 1:01:01. For quick formatting without manual math, timedelta() is convenient.

Use timeit for better benchmarking

The timeit module runs a code snippet many times and reports the average execution time. It is a better choice than one-off timing for measuring short operations where a single run might not be representative.

import timeit
result = timeit.timeit("sum(range(1000))", number=10000)
print(f"Average: {result / 10000:.6f} seconds")

Use classes, decorators, or context managers for reusable timing

In larger codebases, wrapping timer logic in a decorator or context manager avoids repeating the start-end-subtract pattern. These are useful abstractions, but they build on the same fundamentals covered here.

GUI event loops, async timers, and threading.Timer are separate patterns with different use cases. They fall outside the scope of this guide.

Real uses for Python timers

Each timer pattern maps to practical applications you can build or encounter in real work:

Stopwatch (elapsed time tracking):

  • Speed typing tests that measure words per minute
  • Study or focus timers that track session length
  • Fitness interval tracking from the command line

Countdown timer (user-facing countdowns):

  • Exam or quiz time limits
  • Cooking or presentation timers
  • Event countdowns for deadlines or launches

Execution timer (code performance):

Each of these builds directly on the patterns covered in this tutorial. A typing test is a stopwatch. A quiz timer is a countdown. A performance check is an execution timer. The underlying logic stays the same.

Final takeaways

Four key points to carry forward:

  • Use time.time() to measure elapsed time in simple scripts
  • Use time.sleep() to pace a countdown, not to measure time
  • Use divmod() to format seconds into MM:SS for readable output
  • Use time.perf_counter() for more precise performance timing

To create a timer in Python, start by identifying which pattern fits the job: stopwatch, countdown, or execution timer. The right choice depends on whether the goal is tracking elapsed time, counting down for a user, or benchmarking code. Pick the pattern, then build from there.

Build more Python skills with Udacity

Timer scripts are one small example of applied Python programming. The same fundamentals, loops, standard library modules, input handling, extend into automation, data analysis, software development, and AI workflows. Python remains one of the most durable foundations for technical work in the AI economy.

Udacity’s project-based programs move from learning to application, building skills you can demonstrate in real work. Explore the catalog to find programs in Python, data, AI, and software development that match where you want to go next.

Udacity Team
Udacity Team
The Udacity Team is made up of a diverse group of contributors, from technical content developers and curriculum designers to marketing managers, product leaders, and company executives. When a post comes from the Udacity Team, it reflects a collaborative effort to bring you the most accurate, timely, and useful information we can. Our shared mission: helping learners worldwide forge their future in tech.