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.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 12 views 0 copies

Python code

30 lines
Python 3.9+
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."""
    data = json.loads(Path(file_path).read_text(encoding="utf-8"))
    return data


def save_json(file_path: str, data: dict) -> None:
    """Write data to a JSON file with pretty formatting."""
    Path(file_path).write_text(
        json.dumps(data, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )


if __name__ == "__main__":
    sample = {"name": "Beginner", "date": format_today()}
    save_json("sample_output.json", sample)
    loaded = load_json("sample_output.json")
    print(loaded)
    print("File written to:", Path("sample_output.json").resolve())

Output

stdout
{'name': 'Beginner', 'date': '2025-04-12'}
File written to: /path/to/current/directory/sample_output.json

How it works

The format_today function uses datetime.now() to get the current UTC date and time, then applies the specified format pattern. load_json reads a file using pathlib.Path and parses it with json.loads, ensuring proper UTF-8 encoding. save_json writes a dictionary as a pretty-printed JSON with indentation and Unicode preservation. The if __name__ == '__main__' guard prevents these functions from running when the module is imported, but executes them when run as a script.

Common mistakes

  • Forgetting to import `Path` or `json` causing NameError.
  • Using `json.load` instead of `json.loads` for file content strings.
  • Not specifying encoding='utf-8' leading to UnicodeDecodeError.

Variations

  1. Use `date.today()` instead of `datetime.now()` if only the date is needed.
  2. Use `json.dump(file, data)` with a file object instead of writing the string.

Real-world use cases

  • Creating timestamped log files with a standard date format.
  • Persisting API response data to a JSON file for later analysis or caching.
  • Automating configuration file generation and validation in a data pipeline.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.