Modules and Packages · Lesson 27 of 39
A Tour of the Standard Library
Python is famous for being "batteries included": it ships with hundreds of modules for everyday jobs, no installation needed. Knowing what is already there saves you from reinventing the wheel – or installing a package you don't need. Here are the modules you will reach for most.
In this lesson
- Dates and times with
datetime - Random choices with
random - Files and folders with
pathlibandos - Text patterns with
re, and handy tools fromitertools
Standard library highlights
Built in – just import
- Dates & timedatetime, time, zoneinfo, calendar
- Files & systempathlib, os, shutil, sys
- Data formatsjson, csv, sqlite3, zipfile
- Textre, string, textwrap
- Maths & datamath, random, statistics, decimal
- Toolboxcollections, itertools, functools, logging
datetime: dates and times
from datetime import date, datetime, timedelta
exam = date(2026, 12, 15)
today = date(2026, 11, 7)
print("Days left:", (exam - today).days)
print("Revision starts:", exam - timedelta(weeks=4))
meeting = datetime(2026, 11, 7, 15, 30)
print(meeting.strftime("%d %b %Y, %I:%M %p"))
print(datetime.strptime("07/11/2026", "%d/%m/%Y").date())
print(exam.strftime("%A"))
Days left: 38 Revision starts: 2026-11-17 07 Nov 2026, 03:30 PM 2026-11-07 Tuesday
strftime turns a date into text, strptime parses text into a date. In real programs use date.today() or datetime.now() for the current moment, and the zoneinfo module for time zones such as "Asia/Kolkata".
random: chance and shuffling
import random
random.seed(7) # same "random" results every run – useful for tests
print(random.randint(1, 6))
print(random.choice(["rock", "paper", "scissors"]))
cards = ["A", "K", "Q", "J"]
random.shuffle(cards)
print(cards)
print(random.sample(range(1, 50), 6))
3 rock ['K', 'A', 'Q', 'J'] [5, 35, 7, 24, 38, 4]
Security note
random is predictable by design. For passwords, OTPs or tokens use the secrets module: secrets.token_urlsafe(16) or secrets.randbelow(10**6).
pathlib: files and folders
pathlib treats paths as objects and works the same on Windows, macOS and Linux:
from pathlib import Path
reports = Path("reports")
reports.mkdir(exist_ok=True)
file = reports / "summary.txt" # join paths with /
file.write_text("Sales up 12%")
print(file.name, file.suffix, file.stem)
print(file.read_text())
print(file.exists(), sorted(p.name for p in reports.glob("*.txt")))
summary.txt .txt summary Sales up 12% True ['summary.txt']
The older os and os.path functions do similar jobs and you will see them in existing code; os.environ is still the way to read environment variables such as API keys:
import os
print(os.environ.get("APP_MODE", "development"))
development
re: regular expressions
Regular expressions describe text patterns. They look cryptic at first, but a few patterns go a long way:
import re
text = "Call 98765-43210 or 91234-56789, mail help@learnfrenzy.com"
print(re.findall(r"\d{5}-\d{5}", text))
print(re.search(r"[\w.]+@[\w.]+", text).group())
print(re.sub(r"\d", "#", "OTP 4821"))
print(bool(re.fullmatch(r"[A-Z]{5}\d{4}[A-Z]", "ABCDE1234F"))) # PAN format
['98765-43210', '91234-56789'] help@learnfrenzy.com OTP #### True
| Pattern | Matches |
|---|---|
\d / \w / \s | digit / letter, digit or _ / whitespace |
[A-Z] | one character from the range |
+ * ? {5} | one or more / zero or more / optional / exactly 5 |
^ $ | start / end of the text |
itertools: loop superpowers
from itertools import combinations, permutations, product, chain, accumulate
print(list(combinations(["A", "B", "C"], 2)))
print(len(list(permutations("abc"))))
print(list(product([0, 1], repeat=2)))
print(list(chain([1, 2], [3], [4, 5])))
print(list(accumulate([100, 50, 25]))) # running total
[('A', 'B'), ('A', 'C'), ('B', 'C')]
6
[(0, 0), (0, 1), (1, 0), (1, 1)]
[1, 2, 3, 4, 5]
[100, 150, 175]A few more gems
import statistics, textwrap, calendar
marks = [72, 85, 91, 66, 85]
print(statistics.mean(marks), statistics.median(marks), statistics.mode(marks))
print(textwrap.shorten("Python is a wonderful first programming language", width=30))
print(calendar.isleap(2028))
79.8 85 85 Python is a wonderful [...] True
Also worth a look later: json and csv (chapter 11), logging for proper log messages, sqlite3 for a built-in database, argparse for command-line options, and unittest for tests.
Practice
Try it yourself
How many days old is someone born on 15 August 2000, on 7 November 2026?
Show solution
from datetime import date print((date(2026, 11, 7) - date(2000, 8, 15)).days)9580
Extract all hashtags from "Loving #python and #AI at #LearnFrenzy".
Show solution
import re print(re.findall(r"#\w+", "Loving #python and #AI at #LearnFrenzy"))['#python', '#AI', '#LearnFrenzy']
Generate a 6-digit OTP safely.
Show solution
import secrets otp = f"{secrets.randbelow(10**6):06d}" print(len(otp), otp.isdigit())6 True
Quick check
Which function turns a date into formatted text?
strftime(). strptime() does the reverse.
Why use secrets instead of random for OTPs?
random is predictable; secrets uses a cryptographically secure source.
How do you join folder and file names with pathlib?
With the / operator: Path("reports") / "summary.txt".
Summary
- Check the standard library before installing anything.
datetimefor dates,random/secretsfor chance and security,pathlibfor files.refinds patterns in text;itertoolsandstatisticssave many loops.
Interview practice: Python modules, packages and virtual environments.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.