Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
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.
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…
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.
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…
Find Best Meeting Time Across Time Zones in Python
This code calculates overlapping available hours among participants in different time zones and returns the best meeting time in UTC and each participant's local time.
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from dataclasses import dataclass
from typing import List, Tuple, Optional
@dataclass
class Participant:
name: str
timezone: str
# weekdays availability: 0=Mon, start_hour (0-23), end_hour (0-23)
available_slots: List[Tup…
Generate Holiday Calendars for Different Countries in Python
Generate a sorted list of public holidays for a given country and year using Python's calendar and datetime modules.
import calendar
from datetime import date, timedelta
def generate_holiday_calendar(country_code, year=2025):
holidays = []
if country_code == "US":
# New Year's Day
holidays.append(date(year, 1, 1))
# Independence Day
holidays.append(date(year, 7, 4))
# Thanksgivin…
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.
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")
…
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.
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…
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.
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…
Parse WHOIS Data with Python Regex
Extract domain registration fields from a mock WHOIS record using regex and compute days until expiration.
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…
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.
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) !…
Browse by section
Each section groups closely related Python snippets.
Automation & scripting — Python code examples
What you will find here
This page collects automation & scripting snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.