Time Module

Advanced PythonSystemFree Lesson

Advertisement

Introduction

The time module provides time-related functions for performance measurement and scheduling.

Basic Time

import time

# Current time
time.time()          # Unix timestamp
time.ctime()         # Human-readable string

# Sleep
time.sleep(1)        # Sleep for 1 second

# Performance measurement
start = time.time()
# ... code ...
end = time.time()
print(f"Elapsed: {end - start}")

Process Time

import time

# CPU time (not including sleep)
start_cpu = time.process_time()
# ... code ...
end_cpu = time.process_time()

# High resolution
time.perf_counter()  # Most precise for measuring intervals
time.monotonic()    # Never goes backward

Struct Time

import time

now = time.localtime()
print(now.tm_year, now.tm_mon, now.tm_mday)
print(now.tm_hour, now.tm_min, now.tm_sec)

# Format time
formatted = time.strftime("%Y-%m-%d %H:%M:%S", now)

# Parse time
parsed = time.strptime("2024-06-15", "%Y-%m-%d")

Practice Problems

  1. Measure function execution time
  2. Create performance benchmark
  3. Format timestamps for display
  4. Parse various date formats
  5. Implement retry with exponential backoff

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement