androidengineers.Book a session

Python 07 · Files and interchange formats

Dates, time zones, and configuration values

articleSelf-paced

Learn the concept

An event timestamp needs a clear time-zone interpretation. Naive datetimes contain no timezone information; aware datetimes do. Use explicit timezone-aware values for stored events and convert for display. Duration measurement should use a monotonic clock rather than subtracting wall-clock values that can change.

Configuration often arrives as environment-variable strings. Parse and validate it once near startup. The string "false" is nonempty and therefore truthy; convert Boolean configuration explicitly. Missing required configuration should cause a clear startup error.

Avoid placing secrets in source files or examples that will be committed. Log the name of a missing setting rather than printing its secret value. Treat configuration as part of the application contract, with defaults only where they are safe.

Run and inspect

from datetime import datetime, timezone

now = datetime.now(timezone.utc)
assert now.utcoffset().total_seconds() == 0
def parse_flag(text):
    if text not in {"true", "false"}:
        raise ValueError("Expected true or false")
    return text == "true"
assert parse_flag("false") is False

Your exercise

Parse an aware ISO timestamp and a Boolean configuration setting. Reject an ambiguous timestamp unless your application defines a timezone policy.

Check your understanding

You distinguish event timestamps from elapsed time and never rely on bool("false") to parse configuration.

Guided workshop: create an import manifest

An import manifest records what was processed and with which settings. Read text with an explicit encoding, parse interchange formats with libraries, and use timezone-aware timestamps. Do not assemble JSON by concatenating strings: quotes and newlines in content will break it.

# academy-check
import json
from datetime import datetime, timezone
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    target = Path(folder) / "manifest.json"
    manifest = {"source": "guides.jsonl", "accepted": 2,
                "created_at": datetime(2026, 1, 1, tzinfo=timezone.utc).isoformat()}
    target.write_text(json.dumps(manifest, ensure_ascii=False), encoding="utf-8")
    restored = json.loads(target.read_text(encoding="utf-8"))
    assert restored["accepted"] == 2
    assert datetime.fromisoformat(restored["created_at"]).utcoffset().total_seconds() == 0

The temporary directory keeps the exercise isolated. isoformat() includes the UTC offset, so the stored time is not dependent on the reader's timezone. In a real run use datetime.now(timezone.utc) and record the application version separately; a timestamp alone does not identify the code that produced an artifact.

Exercise: convert a CSV with columns id,text to JSON Lines. Include one title containing a comma and one containing a newline. Use csv.DictReader, open the CSV with newline="", and write each record using json.dumps(record) + "\n". Each output record should occupy one physical line even when the text contains an embedded newline, because JSON escapes it.

Worked check: reload each output line with json.loads and compare the records to the parsed CSV. Splitting raw CSV on commas fails for quoted commas; splitting raw JSON Lines on a text field's content fails for escaped newlines.

Checkpoint: configuration values read from the environment are strings. Parse and validate a batch size before opening the source. Keep passwords out of manifests. A source path is not a guarantee that the file's contents stayed unchanged; add a content digest when reproducibility requires it.

YOUR LEARNING JOURNEY

0 of 42 available lessons completed

Progress saved in this browser. No account needed.
Dates, time zones, and configuration values | Python for AI Engineering | Android Engineers