Python's time module provides access to time-related functions at the system level. While datetime handles human-friendly dates, time is for timestamps, delays, and performance measurement.
Current Time
import time
# Unix timestamp (seconds since epoch)
print(time.time()) # 1711022400.123456
# Monotonic clock (for measuring intervals)
print(time.monotonic()) # 123456.789
# Performance counter (highest resolution)
print(time.perf_counter()) # 0.123456789Key Clocks Explained
| Function | Use Case | Can Go Backward? |
|---|---|---|
time() | Wall clock time, timestamps | Yes (NTP sync) |
monotonic() | Measuring duration | No |
perf_counter() | Benchmarking | No |
process_time() | CPU time used | No |
Sleeping / Delays
import time
print("Starting...")
time.sleep(2.5) # Sleep for 2.5 seconds
print("Done!")
# Sub-second sleep
time.sleep(0.1) # 100 millisecondsMeasuring Elapsed Time
import time
# For general timing
start = time.monotonic()
# ... do work ...
elapsed = time.monotonic() - start
print(f"Took {elapsed:.3f} seconds")
# For benchmarking (higher precision)
start = time.perf_counter()
# ... do work ...
elapsed = time.perf_counter() - start
print(f"Took {elapsed:.6f} seconds")Struct Time
Convert between timestamps and structured time:
import time
# Current local time as struct
local = time.localtime()
print(local.tm_year) # 2026
print(local.tm_mon) # 3
print(local.tm_mday) # 21
print(local.tm_hour) # 14
print(local.tm_min) # 30
print(local.tm_wday) # 4 (Friday, 0=Monday)
print(local.tm_yday) # 80 (day of year)
# UTC time as struct
utc = time.gmtime()
# From timestamp
ts = 1711022400
local = time.localtime(ts)
utc = time.gmtime(ts)Formatting Time
import time
# Current time formatted
print(time.strftime("%Y-%m-%d %H:%M:%S"))
# 2026-03-21 14:30:00
# From struct_time
t = time.localtime()
print(time.strftime("%A, %B %d, %Y", t))
# Friday, March 21, 2026
# Common formats
print(time.strftime("%Y-%m-%d")) # 2026-03-21
print(time.strftime("%H:%M:%S")) # 14:30:00
print(time.strftime("%I:%M %p")) # 02:30 PM
print(time.strftime("%Y%m%d_%H%M%S")) # 20260321_143000Parsing Time
import time
# Parse string to struct_time
t = time.strptime("2026-03-21 14:30:00", "%Y-%m-%d %H:%M:%S")
print(t.tm_year) # 2026
print(t.tm_hour) # 14
# Convert to timestamp
ts = time.mktime(t)
print(ts) # 1711042200.0Format Codes
| Code | Meaning | Example |
|---|---|---|
%Y | Year (4 digit) | 2026 |
%m | Month (01-12) | 03 |
%d | Day (01-31) | 21 |
%H | Hour 24h (00-23) | 14 |
%I | Hour 12h (01-12) | 02 |
%M | Minute (00-59) | 30 |
%S | Second (00-59) | 00 |
%p | AM/PM | PM |
%A | Weekday name | Friday |
%B | Month name | March |
%j | Day of year | 080 |
%Z | Timezone name | EST |
Simple Timer Context Manager
import time
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, *args):
self.elapsed = time.perf_counter() - self.start
print(f"Elapsed: {self.elapsed:.4f}s")
# Usage
with Timer():
time.sleep(0.5)
# Elapsed: 0.5012sCPU Time vs Wall Time
import time
# Wall clock time (includes sleeping/waiting)
wall_start = time.perf_counter()
# CPU time (only time spent computing)
cpu_start = time.process_time()
# Do some work
total = sum(i * i for i in range(10_000_000))
time.sleep(1) # This won't count in CPU time
wall_elapsed = time.perf_counter() - wall_start
cpu_elapsed = time.process_time() - cpu_start
print(f"Wall time: {wall_elapsed:.2f}s")
print(f"CPU time: {cpu_elapsed:.2f}s")Timezone Info
import time
# Timezone offset in seconds
print(time.timezone) # e.g., 18000 (5 hours)
print(time.altzone) # DST offset
# Timezone name
print(time.tzname) # ('EST', 'EDT')
# Is DST in effect?
print(time.daylight) # 1 if DST exists
# For current time
t = time.localtime()
print(t.tm_isdst) # 1 if DST activeCommon Patterns
Timestamp to string:
ts = time.time()
s = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))String to timestamp:
s = "2026-03-21 14:30:00"
t = time.strptime(s, "%Y-%m-%d %H:%M:%S")
ts = time.mktime(t)Rate limiting:
import time
def rate_limited_work(items, rate_per_second):
interval = 1.0 / rate_per_second
for item in items:
start = time.monotonic()
process(item)
elapsed = time.monotonic() - start
if elapsed < interval:
time.sleep(interval - elapsed)time vs datetime
- Use
timefor: timestamps, delays, benchmarking, low-level time operations - Use
datetimefor: date arithmetic, formatting, timezone handling, human-friendly dates
# time: raw timestamp
import time
ts = time.time()
# datetime: human-friendly
from datetime import datetime
dt = datetime.now()Summary
The time module is Python's interface to system clocks:
time.time()for timestampstime.sleep()for delaystime.monotonic()/time.perf_counter()for measuring intervalsstrftime()/strptime()for formatting and parsing
For date arithmetic and timezone-aware operations, combine with datetime.
React to this post: