What is the Standard Library?
Python comes with "batteries included" - a rich collection of modules that cover common programming tasks. The standard library includes over 200 modules for everything from text processing to networking. You do not need to install anything - just import and use.
Batteries Included Philosophy
Python ships with a comprehensive standard library so you can accomplish most tasks without installing third-party packages. This reduces dependencies and makes Python programs more portable.
Why it matters: Learning the standard library means you can write powerful programs using only what Python provides out of the box.
Standard Library Module Categories
Text / Data
Math
Date / Time
File / OS
Collections
Random
These are just a few of the many module categories available in Python's standard library.
Common Standard Library Modules
| Module | Purpose | Example Use |
|---|---|---|
datetime | Date and time handling | Get current date, calculate time differences |
random | Random number generation | Generate random numbers, shuffle lists |
os | Operating system interface | List directories, environment variables |
pathlib | Object-oriented paths | Modern file path handling |
collections | Specialized containers | Counter, defaultdict, namedtuple |
math | Mathematical functions | sqrt, sin, cos, pi, e |
json | JSON encoding/decoding | Parse API responses |
re | Regular expressions | Pattern matching in text |
datetime Module
The datetime module provides classes for working with dates and times. You can get the current date and time, perform arithmetic on dates, format dates as strings, and parse strings into dates. It is essential for any application dealing with timestamps.
Getting Current Date and Time
from datetime import datetime, date, time, timedelta
# Current date and time
now = datetime.now()
print(now) # 2026-01-21 14:30:45.123456
# Just the date
today = date.today()
print(today) # 2026-01-21
# Access individual components
print(f"Year: {now.year}") # 2026
print(f"Month: {now.month}") # 1
print(f"Day: {now.day}") # 21
datetime.now() returns the current local date and time with microsecond precision. Use date.today() when you only need the date.
Creating Specific Dates
from datetime import datetime, date
# Create a specific date
birthday = date(1995, 6, 15)
print(birthday) # 1995-06-15
# Create a specific datetime
event = datetime(2026, 12, 31, 23, 59, 59)
print(event) # 2026-12-31 23:59:59
# Parse a date string
date_str = "2026-01-21"
parsed = datetime.strptime(date_str, "%Y-%m-%d")
print(parsed) # 2026-01-21 00:00:00
strptime parses a string into a datetime using format codes. Common codes: %Y (year), %m (month), %d (day), %H (hour), %M (minute).
Date Arithmetic with timedelta
from datetime import datetime, timedelta
now = datetime.now()
# Add days to a date
one_week_later = now + timedelta(days=7)
print(f"One week from now: {one_week_later}")
# Calculate difference between dates
deadline = datetime(2026, 2, 1)
remaining = deadline - now
print(f"Days until deadline: {remaining.days}")
# Complex timedelta
duration = timedelta(hours=5, minutes=30)
meeting_end = now + duration
timedelta represents a duration. Add or subtract it from datetime objects. You can specify days, hours, minutes, seconds, and more.
Formatting Dates as Strings
from datetime import datetime
now = datetime.now()
# Format with strftime
print(now.strftime("%Y-%m-%d")) # 2026-01-21
print(now.strftime("%B %d, %Y")) # January 21, 2026
print(now.strftime("%I:%M %p")) # 02:30 PM
print(now.strftime("%A")) # Wednesday
# ISO format (standard)
print(now.isoformat()) # 2026-01-21T14:30:45.123456
strftime formats a datetime as a string. %B is full month name, %A is full weekday, %I is 12-hour format, %p is AM/PM.
Practice: datetime
Task: Write a function that takes a birth date string (YYYY-MM-DD) and returns the age in days.
Show Solution
from datetime import datetime, date
def age_in_days(birth_str):
birth = datetime.strptime(birth_str, "%Y-%m-%d").date()
today = date.today()
return (today - birth).days
# Test
print(age_in_days("2000-06-15")) # Days since June 15, 2000
Task: Write a function that returns today's date in "Day, Month Date, Year" format (e.g., "Wednesday, January 21, 2026").
Show Solution
from datetime import datetime
def format_today():
return datetime.now().strftime("%A, %B %d, %Y")
# Test
print(format_today()) # Wednesday, January 21, 2026
Task: Write a function that takes a birth date and returns days until the next birthday.
Show Solution
from datetime import date
def days_until_birthday(birth_month, birth_day):
today = date.today()
this_year_bday = date(today.year, birth_month, birth_day)
if this_year_bday < today:
next_bday = date(today.year + 1, birth_month, birth_day)
else:
next_bday = this_year_bday
return (next_bday - today).days
print(days_until_birthday(6, 15)) # Days until June 15
random Module
The random module generates pseudo-random numbers for games, simulations, testing, and any situation where you need unpredictable values. For cryptographic purposes, use the secrets module instead.
Basic Random Functions
import random
# Random float between 0 and 1
print(random.random()) # 0.7234...
# Random integer in range (inclusive)
print(random.randint(1, 6)) # Dice roll: 1-6
# Random choice from a sequence
colors = ["red", "green", "blue"]
print(random.choice(colors)) # e.g., "green"
# Random sample (multiple unique choices)
winners = random.sample(range(1, 100), 3)
print(winners) # e.g., [42, 17, 88]
random.choice picks one item. random.sample picks multiple unique items. randint includes both endpoints.
Shuffling and More
import random
# Shuffle a list in place
deck = list(range(1, 53))
random.shuffle(deck)
print(deck[:5]) # First 5 cards
# Random float in range
temp = random.uniform(20.0, 30.0)
print(f"Temperature: {temp:.1f}")
# Reproducible results with seed
random.seed(42)
print(random.randint(1, 100)) # Always 82
random.seed(42)
print(random.randint(1, 100)) # Always 82 again
shuffle modifies the list in place. Setting a seed makes random numbers reproducible, useful for testing and debugging.
os and pathlib Modules
The os module provides functions for interacting with the operating system. The newer pathlib module offers an object-oriented approach to file paths. Both are essential for file system operations.
os Module Basics
import os
# Current working directory
print(os.getcwd()) # /home/user/project
# List directory contents
files = os.listdir(".")
print(files) # ['main.py', 'data', 'README.md']
# Environment variables
home = os.environ.get("HOME", "Not set")
print(f"Home: {home}")
# Check if path exists
print(os.path.exists("main.py")) # True
print(os.path.isdir("data")) # True
os.getcwd returns the current directory. os.listdir lists contents. os.environ accesses environment variables.
pathlib - Modern Path Handling
from pathlib import Path
# Create path objects
current = Path.cwd()
home = Path.home()
# Build paths with / operator
data_file = current / "data" / "users.json"
print(data_file) # /home/user/project/data/users.json
# Path properties
print(data_file.name) # users.json
print(data_file.suffix) # .json
print(data_file.parent) # /home/user/project/data
print(data_file.exists()) # True or False
pathlib uses the / operator to join paths cleanly. It works across operating systems without worrying about slashes.
Practice: random & os
Task: Write a function that simulates rolling n dice and returns the total.
Show Solution
import random
def roll_dice(n):
total = sum(random.randint(1, 6) for _ in range(n))
return total
# Test - roll 3 dice
print(roll_dice(3)) # e.g., 11
Task: Write a function that generates a random password of length n from letters and digits.
Show Solution
import random
import string
def generate_password(length):
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for _ in range(length))
print(generate_password(12)) # e.g., "aB3kL9mNpQ2x"
Task: Write a function that returns all .py files in a directory using pathlib.
Show Solution
from pathlib import Path
def find_python_files(directory):
path = Path(directory)
return list(path.glob("*.py"))
# Test
py_files = find_python_files(".")
for f in py_files:
print(f.name)
Task: Write a function that returns total size of all files in a directory in KB.
Show Solution
from pathlib import Path
def directory_size_kb(directory):
path = Path(directory)
total = sum(f.stat().st_size for f in path.iterdir() if f.is_file())
return total / 1024
# Test
size = directory_size_kb(".")
print(f"Directory size: {size:.2f} KB")
collections Module
The collections module provides specialized container datatypes beyond the built-in list, dict, set, and tuple. These include Counter for counting, defaultdict for default values, and namedtuple for lightweight objects.
Counter - Count Occurrences
from collections import Counter
# Count items in a list
fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = Counter(fruits)
print(counts) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
# Most common items
print(counts.most_common(2)) # [('apple', 3), ('banana', 2)]
# Count characters in a string
letter_counts = Counter("mississippi")
print(letter_counts) # Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
Counter creates a dictionary mapping items to their counts. most_common returns the n most frequent items as a list of tuples.
defaultdict - Default Values
from collections import defaultdict
# Regular dict raises KeyError for missing keys
# defaultdict provides a default value
# Group items by category
words = ["apple", "ant", "ball", "banana", "cat"]
by_letter = defaultdict(list)
for word in words:
by_letter[word[0]].append(word)
print(dict(by_letter))
# {'a': ['apple', 'ant'], 'b': ['ball', 'banana'], 'c': ['cat']}
defaultdict(list) creates an empty list for missing keys automatically. You can also use int, set, or any callable.
namedtuple - Lightweight Classes
from collections import namedtuple
# Create a Point class with x, y attributes
Point = namedtuple("Point", ["x", "y"])
p1 = Point(10, 20)
p2 = Point(x=5, y=15)
print(p1.x, p1.y) # 10 20
print(p2) # Point(x=5, y=15)
# Useful for structured data
Person = namedtuple("Person", ["name", "age", "city"])
user = Person("Alice", 30, "NYC")
namedtuple creates a simple class with named fields. It is immutable like a tuple but you can access fields by name.
Practice: collections
Task: Write a function that returns the most common word in a list of words.
Show Solution
from collections import Counter
def most_common_word(words):
counts = Counter(words)
return counts.most_common(1)[0][0]
words = ["the", "cat", "sat", "on", "the", "mat", "the"]
print(most_common_word(words)) # "the"
Task: Write a function that groups words by their length using defaultdict.
Show Solution
from collections import defaultdict
def group_by_length(words):
groups = defaultdict(list)
for word in words:
groups[len(word)].append(word)
return dict(groups)
words = ["a", "to", "tea", "ted", "ten", "i", "in"]
print(group_by_length(words))
# {1: ['a', 'i'], 2: ['to', 'in'], 3: ['tea', 'ted', 'ten']}
Task: Create a Student namedtuple with name and grades. Write a function that returns the average grade.
Show Solution
from collections import namedtuple
Student = namedtuple("Student", ["name", "grades"])
def average_grade(student):
return sum(student.grades) / len(student.grades)
alice = Student("Alice", [90, 85, 92, 88])
print(f"{alice.name}: {average_grade(alice):.1f}") # Alice: 88.8
Key Takeaways
Batteries Included
Python's standard library has modules for most common tasks. Check before installing packages.
datetime is Essential
Use datetime for dates and times, timedelta for durations, and strftime/strptime for formatting.
random for Randomness
Use random for games and simulations. Use secrets for cryptographic security.
pathlib over os.path
Prefer pathlib for modern, readable path handling. It works across operating systems.
collections Power
Counter counts, defaultdict provides defaults, namedtuple creates lightweight objects.
Read the Docs
The official Python docs are excellent. Explore them to discover more modules.
Knowledge Check
Quick Quiz
Test what you've learned about Python's standard library