51  Time Module

51.1 Basic

51.1.1 What is the time module?

The time module gives you ways to work with time in your Python programs. This includes: - Getting the current time - Measuring elapsed time - Pausing your program’s execution - Converting between different time formats

  1. time.time() gives you the current time as seconds since the epoch
  2. time.sleep(seconds) pauses your program for the specified duration
  3. localtime() and gmtime() convert epoch time to structured time objects
  4. strftime() formats time objects into human-readable strings
  5. perf_counter() is best for precise performance measurements
  6. process_time() measures only CPU time used by your program

Let’s explore each of these functions with examples.

import time

51.1.2 Getting the current time

The most basic function is time(), which returns the current time as a floating-point number representing seconds since the “epoch” (January 1, 1970, 00:00:00 UTC):

current_time = time.time()
print(current_time)  # Example output: 1712020642.7743263
1746977445.338582

This number by itself isn’t very readable, but it’s useful for calculations and can be converted to more human-readable formats.

51.1.3 Measuring elapsed time

A common use of the time module is measuring how long something takes:

start_time = time.time()

# Code you want to measure
for i in range(1_000_000):
    pass

end_time = time.time()
elapsed_time = end_time - start_time
print(f"Operation took {elapsed_time:.6f} seconds")
Operation took 0.015958 seconds

51.2 Pausing execution with sleep()

To pause your program for a specified number of seconds:

print("Starting...")
time.sleep(2)  # Pause for 2 seconds
print("Continuing after 2 seconds")
Starting...
Continuing after 2 seconds

This is useful for creating delays, implementing simple animations, or rate-limiting API calls.

51.3 Time conversions

51.3.1 Converting epoch time to a structured time

The localtime() and gmtime() functions convert a time expressed in seconds since the epoch to a structured time:

current_time = time.time()
local_time = time.localtime(current_time)  # Local time
utc_time = time.gmtime(current_time)       # UTC time

print(local_time)  
print(utc_time)
time.struct_time(tm_year=2025, tm_mon=5, tm_mday=11, tm_hour=22, tm_min=30, tm_sec=47, tm_wday=6, tm_yday=131, tm_isdst=0)
time.struct_time(tm_year=2025, tm_mon=5, tm_mday=11, tm_hour=15, tm_min=30, tm_sec=47, tm_wday=6, tm_yday=131, tm_isdst=0)

These functions return a struct_time object, which has named attributes like tm_year, tm_mon, etc.

51.3.2 Converting to human-readable format

The strftime() function formats time according to specified format codes:

local_time = time.localtime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print(formatted_time)  # Example output: 2025-04-02 10:30:42
2025-05-11 22:30:47

Common format codes:

  • %Y: 4-digit year (e.g., 2025)
  • %m: Month (01-12)
  • %d: Day (01-31)
  • %H: Hour in 24-hour format (00-23)
  • %M: Minute (00-59)
  • %S: Second (00-59)
  • %A: Weekday name (e.g., Wednesday)
  • %B: Month name (e.g., April)

51.3.3 Converting string to time

The strptime() function parses a string representation of time:

time_string = "2025-04-02 10:30:42"
parsed_time = time.strptime(time_string, "%Y-%m-%d %H:%M:%S")
print(parsed_time)  # Returns a struct_time object

51.3.4 Performance measurement with perf_counter()

For more precise timing, especially for benchmarking code, use perf_counter():

start = time.perf_counter()
# Code to measure
time.sleep(0.1)  # Just as an example
end = time.perf_counter()
print(f"Operation took {end - start:.6f} seconds")
Operation took 0.105405 seconds

perf_counter() is more accurate than time() for measuring short durations and isn’t affected by system clock changes.

51.3.5 Processor time with process_time()

To measure only CPU time used by your program (excluding sleep time):

start = time.process_time()
# Code to measure
time.sleep(1)  # This won't be counted in process_time
end = time.process_time()
print(f"CPU time used: {end - start:.6f} seconds")
CPU time used: 0.001698 seconds

51.4 Example

51.4.1 Countdown

def countdown(seconds):
    """
    Count down from the specified number of seconds.
    
    Parameters
    ----------
    seconds : int
        Number of seconds to count down from
    """
    print(f"Countdown starting from {seconds} seconds...")
    
    for remaining in range(seconds, 0, -1):
        print(f"{remaining} seconds remaining")
        time.sleep(1)
        
    print("Time's up!")

# Usage
countdown(5)
Countdown starting from 5 seconds...
5 seconds remaining
4 seconds remaining
3 seconds remaining
2 seconds remaining
1 seconds remaining
Time's up!