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.
Python code
30 linesfrom 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
{'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
- Use `date.today()` instead of `datetime.now()` if only the date is needed.
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.