Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

34 matches
Strings & text easy

How to Detect Expired Domains Using Python

Parse a list of domain registration data and compare expiry dates to today to find expired domains.

datetime date-parsing domain-check
Python
import datetime

# List of test domains with fake registration and expiry dates
# Format: (domain, registration_date, expiry_date)
test_domains = [
    ('example.com', '2020-01-15', '2024-01-15'),  # Expired
    ('google.com', '1997-09-15', '2026-09-15'),   # Still active
    ('test-site.org', '2019-06-01', '2023-06-0…
50 0 Open
Lists & loops easy

Find Most Active Contributors in a Repository with Python

Filter recent commits by date and count the most active contributors using Counter and datetime.

collections datetime counter
Python
from collections import Counter
from datetime import datetime, timedelta

# Simulated commit data
commits = [
    {"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
    {"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
    {"author": "Alice", "timestamp": datetime.now() - timedelta…
44 0 Open
Functions & basics easy

Calculate Time Difference Across Time Zones in Python

Compute the current time difference in hours between two time zones given their UTC offsets using Python's datetime and timezone modules.

datetime timezone timedelta
Python
from datetime import datetime, timezone, timedelta

def time_difference(from_tz_offset, to_tz_offset):
    """
    Calculate time difference in hours between two time zones given their offsets from UTC.
    Offsets are in hours (e.g., -5 for EST, +5.5 for IST).
    """
    tz1 = timezone(timedelta(hours=from_tz_offset…
44 0 Open
Files & data easy

How to Archive Old Files by Age in Python

Move files older than a specified number of days from a source directory to an archive directory using Python's pathlib and shutil modules.

file-archiving pathlib shutil
Python
import os
import shutil
import time
from pathlib import Path

def archive_old_files(source_dir: str, archive_dir: str, days_old: int) -> None:
    cutoff_time = time.time() - (days_old * 86400)  # 86400 seconds in a day
    archive_path = Path(archive_dir)
    archive_path.mkdir(parents=True, exist_ok=True)

    for i…
46 0 Open
Files & data easy

How to Build a Dated Backup Filename with Timestamp in Python

Generate unique backup filenames with a timestamp using Python's datetime module and f-strings.

datetime backup filenames
Python
from datetime import datetime

def build_backup_filename(base_name: str, extension: str = "bak") -> str:
    """Generate a dated backup filename with timestamp."""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    return f"{base_name}_{timestamp}.{extension}"

if __name__ == "__main__":
    backup_file = bu…
12 0 Open
Dictionaries & sets easy

Serialize Python dict to JSON with custom default for datetime

Convert a Python dict containing datetime and set objects into JSON by providing a custom default serializer.

json datetime serialization
Python
import json
from datetime import datetime

def custom_serializer(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    if isinstance(obj, set):
        return list(obj)
    return str(obj)

data = {
    "name": "Alice",
    "created_at": datetime(2024, 3, 15, 10, 30, 45),
    "tags": {"python", "j…
15 0 Open
Automation & scripting easy

Aggregate Log Errors Count by Hour in Python

Counts ERROR log lines per hour using regex and Counter, returning a sorted dictionary of hourly totals.

logs regex counter
Python
import re
from collections import Counter
from datetime import datetime

def aggregate_errors_by_hour(log_lines):
    pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2}.*ERROR')
    hourly_counts = Counter()
    
    for line in log_lines:
        match = pattern.match(line)
        if match:
            ho…
20 0 Open
Automation & scripting easy

Build a Live Countdown Timer for Events in Python

A Python script that displays a real-time countdown to a target date and time, updating every second in the console.

datetime countdown timers
Python
import datetime
import time

def countdown(event_name, target_datetime):
    """Displays a live countdown to a target datetime."""
    while True:
        now = datetime.datetime.now()
        remaining = target_datetime - now
        if remaining.total_seconds() <= 0:
            print(f"\n🚀 {event_name} is happening…
45 0 Open
Automation & scripting easy

How to Backup an SQLite Database with a Timestamp in Python

Backs up an SQLite database file to a timestamped copy using the sqlite3 backup API.

sqlite backup automation
Python
import sqlite3
import shutil
from datetime import datetime
from pathlib import Path

def backup_database(db_path: str, backup_dir: str = "backups") -> Path:
    db = Path(db_path)
    backup_folder = Path(backup_dir)
    backup_folder.mkdir(exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 …
13 0 Open
Automation & scripting easy

How to Filter Docker Containers for Pruning in Python

Simulate Docker's container prune by filtering a JSON list for exited containers older than a cutoff, returning pruned IDs and space freed.

docker json datetime
Python
import json
from datetime import datetime, timedelta


def parse_docker_ps(json_output: str, older_than_hours: int = 24) -> list:
    containers = json.loads(json_output)
    cutoff = datetime.now() - timedelta(hours=older_than_hours)
    return [
        c for c in containers
        if datetime.fromisoformat(c["crea…
13 0 Open
Automation & scripting easy

How to Find Stale GitHub Issues in Python

Filter a list of GitHub issues to find those not updated within a configurable number of days using Python datetime arithmetic.

github issues automation
Python
import os
from datetime import datetime, timezone, timedelta
import re

# Simulated GitHub issue data structure
SAMPLE_ISSUES = [
    {"number": 101, "title": "Login button not working", "updated_at": "2025-06-01T12:00:00Z", "assignee": "alice"},
    {"number": 102, "title": "Fix database migration error", "updated_at…
35 0 Open
Automation & scripting easy

Parse WHOIS Data with Python Regex

Extract domain registration fields from a mock WHOIS record using regex and compute days until expiration.

whois regex parsing
Python
import re
from datetime import datetime


def parse_whois(whois_text: str) -> dict:
    """Extract key registration fields from a mock WHOIS record."""
    patterns = {
        "domain": r"Domain Name:\s*(.+)",
        "registrar": r"Registrar:\s*(.+)",
        "creation_date": r"Creation Date:\s*(.+)",
        "expir…
12 0 Open
Automation & scripting easy

Parse cron expression and compute next run datetime in Python

Parse a 5-field cron expression and compute the next matching datetime starting from a given base time.

cron datetime scheduling
Python
from datetime import datetime, timedelta
import re

def parse_cron_and_next_run(cron_expr, base_time=None):
    """Parse a cron expression and compute the next run time."""
    if base_time is None:
        base_time = datetime.now().replace(second=0, microsecond=0)

    fields = cron_expr.split()
    if len(fields) !…
11 0 Open
Data pipelines & processing easy

Group Python Events into Sessions with a Gap Timeout

Groups timestamped events into sessions, starting a new session when the time gap exceeds a specified timeout.

sessions grouping datetime
Python
from itertools import groupby
from datetime import datetime, timedelta

def session_window_group(events, gap_seconds=300):
    """Group events into sessions where gap > gap_seconds starts a new session."""
    if not events:
        return []
    
    events = sorted(events, key=lambda x: x[0])
    sessions = []
    c…
13 0 Open
Data pipelines & processing easy

How to Convert Data Types in a Python Data Pipeline

Demonstrates a simple Python data pipeline that converts string values to proper types (bool, int, float, datetime) and outputs structured JSON.

data-pipeline type-conversion json
Python
import json
from datetime import datetime

def convert_value(value):
    """Convert string values to appropriate Python types."""
    if value.lower() == "true":
        return True
    if value.lower() == "false":
        return False
    if value.isdigit():
        return int(value)
    try:
        return float(val…
11 0 Open
Data pipelines & processing easy

How to Parse Data in Python: A Beginner's Helper

This helper parses a JSON payload, extracts user names, emails, and signup dates, then summarizes the results.

json parsing data-processing
Python
import json
from datetime import datetime
from typing import Dict, List


def parse_data(payload: str) -> Dict[str, List]:
    """Parse a JSON payload and extract useful fields."""
    raw = json.loads(payload)
    users = raw.get("users", [])

    parsed = {
        "names": [],
        "emails": [],
        "signup_…
15 0 Open
Data pipelines & processing easy

Rollback dataset to previous snapshot pointer in Python

A SnapshotManager class stores timestamped data snapshots and rolls back to the most recent snapshot at or before a target time.

snapshots rollback datetime
Python
from datetime import datetime, timedelta


class SnapshotManager:
    def __init__(self):
        self.snapshots = {}  # timestamp -> data
        self.current_pointer = None

    def create_snapshot(self, data):
        timestamp = datetime.now()
        self.snapshots[timestamp] = data
        self.current_pointer =…
13 0 Open
Cloud + Python easy

Mock ECS Task Run Stop Status Dict in Python

Build a mock ECS task status dictionary with RUNNING/STOPPED states using the standard library.

aws ecs mocking
Python
from datetime import datetime, timezone


def mock_ecs_task_status(task_id: str, state: str = "RUNNING") -> dict:
    """Return a mock ECS task status dictionary."""
    return {
        "taskArn": f"arn:aws:ecs:us-east-1:123456789012:task/cluster/{task_id}",
        "taskDefinition": "arn:aws:ecs:us-east-1:1234567890…
15 0 Open
Modern tooling easy

Data Conversion Helper Functions in Python

A set of beginner-friendly helper functions to convert between JSON strings and Python data, parse dates, and read/write files using pathlib.

json datetime pathlib
Python
from datetime import datetime
from pathlib import Path
import json

def to_json(data, indent=2):
    """Convert Python data to pretty-printed JSON string."""
    return json.dumps(data, indent=indent, default=str)

def from_json(json_string):
    """Parse JSON string back into Python data."""
    return json.loads(jso…
12 0 Open
Modern tooling easy

How to Format Data with Python's datetime and JSON Helpers

A beginner-friendly set of helper functions to format dates and safely read/write JSON files in Python.

datetime json files
Python
from datetime import datetime
from pathlib import Path
import json


def format_today(pattern: str = "%Y-%m-%d") -> str:
    """Return today's date formatted with the given pattern."""
    return datetime.now().strftime(pattern)


def load_json(file_path: str) -> dict:
    """Read and parse a JSON file safely."""
    …
12 0 Open
Testing & modern typing easy

How to freeze time in Python tests with freezegun

Use the freezegun decorator to freeze datetime.now() at a fixed timestamp so tests that depend on current time run deterministically.

freezegun datetime testing
Python
from datetime import datetime
from freezegun import freeze_time


@freeze_time("2024-01-15 12:30:00")
def test_frozen_time():
    now = datetime.now()
    return now


if __name__ == "__main__":
    result = test_frozen_time()
    print(result)
15 0 Open
Testing & modern typing easy

Mock datetime with time-machine in Python

Use the time-machine library to travel to a fixed datetime when running tests or scripts, mocking datetime.utcnow().

testing datetime mock
Python
from time_machine import travel
from datetime import datetime


@travel("2020-01-01 10:30:00")
def check_date():
    return datetime.utcnow()


if __name__ == "__main__":
    print(check_date())
13 0 Open
Testing & modern typing easy

Mock datetime.now to freeze time in Python

Use unittest.mock.patch to replace datetime.now with a fixed value so your code always sees the same time during tests.

datetime mock unittest
Python
from datetime import datetime
from unittest.mock import patch

def current_message():
    now = datetime.now()
    return f"Current time: {now:%Y-%m-%d %H:%M:%S}"

if __name__ == "__main__":
    with patch("__main__.datetime") as mock_dt:
        mock_dt.now.return_value = datetime(2024, 3, 15, 10, 30, 0)
        prin…
14 0 Open
Streaming & messaging easy

How to Serialize and Deserialize JSON Event Payloads in Python

Define an EventPayload class with custom to_json and from_json methods to convert event objects to JSON strings and back, using datetime parsing.

json serialization datetime
Python
import json
from datetime import datetime


class EventPayload:
    def __init__(self, event_id, event_type, timestamp, data):
        self.event_id = event_id
        self.event_type = event_type
        self.timestamp = timestamp
        self.data = data

    def to_json(self):
        return json.dumps({
          …
12 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.