Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

4 matches
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
Observability & SRE medium

How to Implement an Error Budget Policy in Python

This code implements a mock error budget policy that decides whether to freeze deployments based on a simulated error rate and monthly freeze limits.

error-budget sre deploy-freeze
Python
from datetime import datetime, timedelta

class ErrorBudgetPolicy:
    FREEZE_WINDOW_HOURS = 24
    MAX_FREEZES_PER_MONTH = 3

    def __init__(self, budget_percentage=99.9):
        self.budget_percentage = budget_percentage
        self.freeze_count = 0
        self.last_freeze_start = None
        self.freeze_enabl…
13 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.