The Standard Library

Python ships with a huge library of ready-made modules.

Syntaximport datetime, json, random

Python comes with "batteries included" — a large standard library of modules you can import without installing anything.

A few favourites

  • random — random numbers and choices.
  • datetime — dates and times.
  • json — read and write JSON.
  • os and pathlib — files and paths.

Example

Example · python
import json
from datetime import date

data = {'name': 'Ada', 'age': 36}
text = json.dumps(data)
print(text)

print(date(2026, 7, 15).year)

# Output:
# {"name": "Ada", "age": 36}
# 2026

When to use it

  • A script uses 'random.choice()' to select a random quiz question from a prepared list.
  • A backup tool uses 'shutil.copy()' to duplicate files without writing OS-specific shell commands.
  • A scheduler uses 'datetime.now()' to timestamp each log entry with the current date and time.

More examples

random module

Uses the random module for number generation, random selection, and in-place shuffling.

Example · python
import random

print(random.randint(1, 100))         # random int 1-100
colours = ['red', 'green', 'blue']
print(random.choice(colours))        # one colour at random
random.shuffle(colours)
print(colours)                        # shuffled list

datetime module

Gets the current timestamp, formats it as a string, and computes a deadline 7 days later.

Example · python
from datetime import datetime, timedelta

now = datetime.now()
print(now.strftime('%Y-%m-%d %H:%M'))   # 2024-05-01 14:30
deadline = now + timedelta(days=7)
print(deadline.date())                  # 2024-05-08

os and pathlib modules

Uses pathlib.Path for object-oriented path manipulation and glob to list Python files.

Example · python
from pathlib import Path

cwd = Path.cwd()
logs = cwd / 'logs'
print(logs)                    # .../logs
print(logs.exists())          # True or False
for f in cwd.glob('*.py'):
    print(f.name)

Discussion

  • Be the first to comment on this lesson.