Back to Blog
Python Modules and Standard Library Highlights

Python Modules and Standard Library Highlights

November 24, 2026
Reynov Christian

One of Python’s biggest strengths is its “batteries included” philosophy. When you install Python, you do not just get the core language. You also get hundreds of built-in modules (ready-made Python files packed with useful functions) called the Python Standard Library.

Instead of writing date math, random number logic, or file tools from scratch, you can import them in one line. In this lesson, you will learn how the import statement works, explore four essential modules (math, random, datetime, and sys), and build a Password and Security Token Generator with Date Expiry.

1. How the import Statement Works

A module is simply a file containing Python code you can reuse. You have already used from pathlib import Path, import csv, and import json in earlier lessons. Python gives you three clean ways to import a module:

# 1. Import the whole module
import math
print(math.sqrt(81))  # 9.0

# 2. Import only specific items from a module
from math import ceil, floor
print(ceil(4.2))      # 5
print(floor(4.8))     # 4

# 3. Give a module a shorter alias with "as"
import datetime as dt
print(dt.date.today())

Avoid writing from math import *. Importing everything into your file hides where functions came from and can accidentally overwrite your own variable names.

2. Math and System Tools: math and sys

The math module gives you reliable mathematical functions and constants like math.pi, math.sqrt(), and math.ceil(). The sys module lets your script inspect the Python environment itself, such as the running Python version or command-line arguments.

import math
import sys

radius = 5.0
area = math.pi * (radius ** 2)
print(f"Circle area: {area:.2f}")

# Check which Python version is running your script
print(f"Python version: {sys.version.split()[0]}")
print(f"Operating system: {sys.platform}")

Checking sys.version is handy when troubleshooting scripts across different computers, and sys.exit() lets you stop a program cleanly when a required condition is not met.

3. Working with Dates and Timestamps: datetime

Handling dates by hand is notoriously tricky because of leap years and varying month lengths. Python’s datetime module handles all of that for you. Use datetime.now() for the current date and time, timedelta to add or subtract days, and .strftime() to format dates as readable strings.

from datetime import datetime, timedelta

now = datetime.now()
expires = now + timedelta(days=7)

print("Created:", now.strftime("%Y-%m-%d %H:%M"))
print("Expires:", expires.strftime("%Y-%m-%d %H:%M"))

Format codes like %Y (4-digit year), %m (month), %d (day), %H (24-hour clock), and %M (minute) give you complete control over how timestamps appear in logs and reports.

4. Randomness: random vs. secrets

The random module is great for games, simulations, and picking sample items from a list:

import random

dice_roll = random.randint(1, 6)
colors = ["red", "blue", "green", "yellow"]
picked = random.choice(colors)

print(f"You rolled a {dice_roll} and picked {picked}.")

Here is an important modern Python habit: random is predictable under the hood, so it is meant for games and tests, not security. Whenever you generate real passwords, reset links, or API tokens, use Python’s built-in secrets module instead. It uses your operating system’s cryptographic randomness and is just as easy to call.

5. Practical Project: Password and Security Token Generator with Date Expiry

Let’s combine secrets, string, datetime, json, and pathlib into a practical CLI tool. Create a file named token_generator.py. It generates strong passwords or URL-safe security tokens with an expiration date and saves a clean JSON record to tokens.json.

At the bottom of the script, if __name__ == "__main__": is a standard Python guard that runs main() only when you execute this file directly (we will explore how that works in Lesson 15).

import json
import secrets
import string
import sys
from datetime import datetime, timedelta
from pathlib import Path

TOKENS_FILE = Path("tokens.json")


def generate_password(length: int) -> str:
    """Generate a cryptographically strong random password."""
    alphabet = string.ascii_letters + string.digits + "!@#$%&*"
    return "".join(secrets.choice(alphabet) for _ in range(length))


def create_token_record(label: str, valid_days: int) -> dict[str, str]:
    """Create a URL-safe security token with creation and expiry timestamps."""
    now = datetime.now()
    expires = now + timedelta(days=valid_days)
    return {
        "label": label,
        "token": secrets.token_urlsafe(16),
        "created_at": now.strftime("%Y-%m-%d %H:%M"),
        "expires_at": expires.strftime("%Y-%m-%d %H:%M"),
    }


def load_tokens(file_path: Path) -> list[dict[str, str]]:
    """Load saved token records from JSON, returning an empty list if missing."""
    if not file_path.exists():
        return []
    try:
        content = file_path.read_text(encoding="utf-8").strip()
        if not content:
            return []
        data = json.loads(content)
        return data if isinstance(data, list) else []
    except json.JSONDecodeError:
        print("Warning: tokens.json is invalid. Starting with an empty list.")
        return []


def save_tokens(file_path: Path, tokens: list[dict[str, str]]) -> None:
    """Write token records to a formatted JSON file."""
    with open(file_path, "w", encoding="utf-8") as file:
        json.dump(tokens, file, indent=4)


def get_valid_int(prompt: str, minimum: int, maximum: int) -> int:
    """Ask the user for a whole number within a safe range."""
    while True:
        try:
            value = int(input(prompt))
            if minimum <= value <= maximum:
                return value
            print(f"Please enter a number between {minimum} and {maximum}.")
        except ValueError:
            print("Invalid input. Please enter a whole number.")


def main() -> None:
    """Run the Password and Security Token Generator CLI."""
    print(f"Security Token Generator (Python {sys.version.split()[0]})")
    tokens = load_tokens(TOKENS_FILE)

    while True:
        print("\nMenu:")
        print("1. Generate Strong Password")
        print("2. Create Expiring Security Token")
        print("3. View Saved Tokens")
        print("4. Exit")

        choice = input("Choose an option (1-4): ").strip()

        if choice == "1":
            length = get_valid_int("Password length (8 to 64): ", 8, 64)
            password = generate_password(length)
            print(f"Generated password: {password}")
        elif choice == "2":
            label = input("Token label (e.g., Staging API): ").strip()
            if not label:
                print("Label cannot be empty.")
                continue
            days = get_valid_int("Valid for how many days (1 to 365)? ", 1, 365)
            record = create_token_record(label, days)
            tokens.append(record)
            save_tokens(TOKENS_FILE, tokens)
            print(f"Token created: {record['token']}")
            print(f"Expires on:    {record['expires_at']}")
        elif choice == "3":
            if not tokens:
                print("No tokens saved yet.")
                continue
            print("\n--- Saved Tokens ---")
            for item in tokens:
                print(
                    f"- {item['label']} | {item['token']} | "
                    f"Expires: {item['expires_at']}"
                )
        elif choice == "4":
            print("Goodbye!")
            break
        else:
            print("Invalid choice. Please enter 1, 2, 3, or 4.")


if __name__ == "__main__":
    main()

Run python token_generator.py from your terminal. Try generating a 16-character password and creating a token valid for 7 days, then open tokens.json to see the saved timestamps.

Common Beginner Mistakes

  • Naming your file after a standard module: If you name your own script random.py or datetime.py, Python will import your file instead of the built-in module and fail with an AttributeError. Always pick descriptive names like token_generator.py.
  • Using random for security passwords: random.choice() is fine for games, but use secrets.choice() or secrets.token_urlsafe() for passwords and tokens.
  • Mixing up %m and %M in strftime(): Lowercase %m is the month (01 to 12), while uppercase %M is the minute (00 to 59).
  • Using wildcard imports (from math import *): Wildcard imports pollute your file with dozens of hidden names and make debugging harder. Import the module or only the exact functions you need.

Try It Yourself

  • Expiry Checker (check_expired_tokens.py): Load tokens.json, parse each expires_at string with datetime.strptime(value, "%Y-%m-%d %H:%M"), and print whether each token is still active or expired.
  • Dice Simulator (dice_stats.py): Use random.randint(1, 6) to roll a die 100 times and print how many times each face (1 to 6) appeared using a dictionary.
  • Countdown Calculator (days_until.py): Ask the user for a future date (YYYY-MM-DD), parse it with datetime.strptime(), and print how many days remain from today.

Frequently Asked Questions

Do I need to install math, random, datetime, or secrets with pip?

No. All of them are part of the Python Standard Library, so they are already installed with Python 3.14.

Why did my script fail with AttributeError: module ‘random’ has no attribute ‘randint’?

That almost always means you have a file named random.py in the same folder. Rename your file to something else (like dice_game.py) and run it again.

When should I use import module vs. from module import name?

Use import math when you call several functions from a module and want clear prefixes like math.sqrt(). Use from pathlib import Path when you only need one or two specific classes or functions.

What does secrets.token_urlsafe(16) return?

It creates 16 random bytes and encodes them into a URL-safe text string (letters, numbers, hyphens, and underscores) that you can safely use in links, headers, or JSON files.

Need to review how our project saves data to JSON? Check out the previous lesson: Working with JSON Data: Python and Web Standards. In our next article, Virtual Environments and Package Management with Pip, you will learn how to install third-party libraries cleanly without breaking your system Python.

Learning programming works best as a collaborative process, and your questions and insights help make these tutorials more effective for everyone. If you get stuck with date formatting, hit a module naming conflict, or add a new feature to the token generator, please share your experience in the comments. Your feedback helps create a learning community where we can all benefit from each other’s discoveries and solutions.

You Might Also Like

Comments

Loading comments…

Leave a Comment

0/5000