Files, JSON, CSV and dates
Pipelines read files, decode JSON and CSV, and decide which days to process. Each has a trap that causes real outages: a CSV split on commas, %M where %m was meant, a day boundary in the wrong time zone. This lesson covers files, JSON, CSV, dates and time zones, in plain words.
Foundations · Python for data engineers · Bronze · Python basics for data engineers, lesson 3 of 3
On this page
In plain words first
A file: a long scroll
JSON: a parcel with a packing list
A datetime with a time zone: a wall clock with a city label
Reading and writing files
Open files with with open(...), so they are closed even when an error happens halfway. Always pass encoding="utf-8": the default depends on the machine. Looping over the file reads one line at a time, so memory stays flat however big the file is. pathlib.Path treats paths as objects: folder / "orders.log" joins parts correctly on every operating system.
from pathlib import Path folder = Path("exports") folder.mkdir(exist_ok=True) log_file = folder / "orders.log" log_file.write_text("o1 placed\no2 placed\no1 delivered\n", encoding="utf-8") with open(log_file, encoding="utf-8") as f: # closed for you, even after an error for number, line in enumerate(f, start=1): # one line at a time print(number, line.rstrip("\n")) print("log files:", sorted(p.name for p in folder.glob("*.log"))) print("name parts:", log_file.stem, log_file.suffix)
Output from a real run
1 o1 placed 2 o2 placed 3 o1 delivered log files: ['orders.log'] name parts: orders .log
JSON: dumps and loads
json.dumps turns dicts, lists, strings, numbers, booleans and None into JSON text; json.loads turns it back. Anything else, such as a date, raises TypeError: default=str tells dumps to convert such values with str(). indent and sort_keys make the text readable and stable.
import json from datetime import date order = {"id": 7, "items": ["dosa", "chai"], "paid": True, "note": None} text = json.dumps(order) print(text) # JSON spells them true and null print(json.loads(text) == order) # and back to the same dict try: json.dumps({"day": date(2026, 3, 1)}) except TypeError: print("a date is not JSON: pass default=str") print(json.dumps({"day": date(2026, 3, 1)}, default=str)) print(json.dumps({"b": 1, "a": [1, 2]}, indent=2, sort_keys=True))
Output from a real run
{"id": 7, "items": ["dosa", "chai"], "paid": true, "note": null}
True
a date is not JSON: pass default=str
{"day": "2026-03-01"}
{
"a": [
1,
2
],
"b": 1
}CSV and JSON lines
Do not split CSV lines on commas yourself: "fast, polite" has a comma inside quotes. The csv module handles quoting. DictReader gives each row as a dict keyed by the header, DictWriter writes dicts back, and both want the file opened with newline="". JSON lines (.jsonl) holds one JSON object per line, so it can be read record by record.
import csv import json from pathlib import Path with open("riders.csv", "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=["rider", "city", "note"]) writer.writeheader() writer.writerow({"rider": "asha", "city": "Pune", "note": "fast, polite"}) writer.writerow({"rider": "ben", "city": "Goa", "note": ""}) with open("riders.csv", newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f)) print(rows[0]) print("the comma stayed inside its field:", rows[0]["note"]) Path("events.jsonl").write_text('{"id": 1, "ok": true}\n{"id": 2, "ok": false}\n') with open("events.jsonl", encoding="utf-8") as f: events = [json.loads(line) for line in f if line.strip()] print(events)
Output from a real run
{'rider': 'asha', 'city': 'Pune', 'note': 'fast, polite'}
the comma stayed inside its field: fast, polite
[{'id': 1, 'ok': True}, {'id': 2, 'ok': False}]Every value from csv is a string, even numbers, and an empty field is "", not None. Convert types yourself and decide what an empty field means.
Dates and durations
date is a day, datetime a day and a time, timedelta a length of time. Adding a timedelta to a date gives another date, with month lengths and leap years handled for you.
from datetime import date, timedelta start = date(2026, 2, 26) print("plus 3 days:", start + timedelta(days=3)) # February 2026 has 28 days print("days until 1 April:", (date(2026, 4, 1) - start).days) print("weekday (Monday is 0):", start.weekday()) # A backfill: one run per day, both ends included. day, last = start, date(2026, 3, 2) while day <= last: print("run for", day.isoformat()) day += timedelta(days=1)
Output from a real run
plus 3 days: 2026-03-01 days until 1 April: 34 weekday (Monday is 0): 3 run for 2026-02-26 run for 2026-02-27 run for 2026-02-28 run for 2026-03-01 run for 2026-03-02
Parsing and formatting: ISO 8601, strptime and strftime
ISO 8601 is the standard shape, 2026-03-01T18:45:00+05:30: fromisoformat reads it, including a trailing Z for UTC. Anything else needs strptime with a format; strftime writes one. Prefer ISO whenever you pick the format: it sorts correctly as text. Two pairs of codes cause most bugs: %m is the month but %M the minute, and %Y is a four-digit year while %y is two digits.
from datetime import datetime placed = datetime.fromisoformat("2026-03-01T18:45:00+05:30") # ISO 8601 print(placed, "| hour:", placed.hour) print(datetime.fromisoformat("2026-03-01T13:15:00Z")) # Z means UTC typed = datetime.strptime("01/03/26 6:45 PM", "%d/%m/%y %I:%M %p") print(typed, "| %y read 26 as", typed.year) print("for a report:", typed.strftime("%d %b %Y, %H:%M")) late = datetime(2026, 3, 1, 18, 5) print("%m is the month:", late.strftime("%Y-%m-%d")) print("%M is the MINUTE:", late.strftime("%Y-%M-%d")) # a silent wrong date
Output from a real run
2026-03-01 18:45:00+05:30 | hour: 18 2026-03-01 13:15:00+00:00 2026-03-01 18:45:00 | %y read 26 as 2026 for a report: 01 Mar 2026, 18:45 %m is the month: 2026-03-01 %M is the MINUTE: 2026-05-01
Time zones: naive, aware and zoneinfo
A datetime without a time zone is naive: "2:30 am", but where? One with a zone is aware, a real moment. Keep datetimes aware, store them in UTC, and convert to a local zone only to show them or to decide which local day something belongs to.
from datetime import datetime, timedelta, timezone IST = timezone(timedelta(hours=5, minutes=30), "IST") placed = datetime(2026, 3, 2, 2, 30, tzinfo=IST) # 2:30 am on 2 March in India in_utc = placed.astimezone(timezone.utc) print("IST:", placed.isoformat()) print("UTC:", in_utc.isoformat()) print("same moment:", placed == in_utc, "| but the UTC date is", in_utc.date()) naive = datetime(2026, 3, 2, 2, 30) # no time zone: which 2:30? try: print(naive < placed) except TypeError: print("TypeError: a naive and an aware datetime cannot be compared")
Output from a real run
IST: 2026-03-02T02:30:00+05:30 UTC: 2026-03-01T21:00:00+00:00 same moment: True | but the UTC date is 2026-03-01 TypeError: a naive and an aware datetime cannot be compared
An order at 2:30 am in India on 2 March belongs to 1 March in UTC, so "orders per day" depends on whose day you count. Pick the zone that defines a day for the business and convert before grouping by date.
from zoneinfo import ZoneInfo and ZoneInfo("Europe/London"), which knows the rules. Noon on 15 January there is 12:00:00+00:00; noon on 15 July is 12:00:00+01:00.Common mistakes
- Splitting CSV lines on commas — Quoted values with commas shift the columns. Use csv.DictReader.
- Writing %M for the month — %M is minutes, so the date is silently wrong. Month is %m; prefer ISO format.
- Mixing naive and aware datetimes — Comparing them raises TypeError, and guessing the zone shifts data by hours. Attach a zone to every datetime.
- Grouping by date before converting the time zone — Late-night events land on the wrong day. Convert to the business zone, then take the date.
Key takeaways
- Loop over an open file to read it one line at a time, with flat memory.
- json.dumps(..., default=str) handles dates; indent and sort_keys make stable, readable output.
- csv returns strings: convert types and decide what "" means.
- date + timedelta knows month lengths and leap years.
- ISO 8601 text sorts correctly as plain text, and fromisoformat reads it, Z included.
Interview prep
THE QUESTION
"A daily report shows different totals in India and in London for the same day. Why, and how would you fix it?"
Avoid: "I would store local times and convert when needed". Without a zone attached, nobody knows later which local time it was. Store aware UTC timestamps and convert at the edges.
Follow-ups · answer out loud, then open
Follow-up"How would you run a backfill for every day between two dates?"
Scenario"A 40 GB CSV export has to be cleaned on a machine with 8 GB of memory."
Trap"Splitting each line on commas is enough to read a CSV."
Check yourself
4 questionsdate(2026, 2, 28) + timedelta(days=1) is...
Show the answer
2026-03-01. February 2026 has 28 days; timedelta knows the calendar.
Which format code is the month?
Show the answer
%m. %m is the month as a number; %M is the minute.
json.dumps({"day": date(2026, 3, 1)}) without default=...
Show the answer
Raises TypeError. JSON has no date type, so dumps needs default=str (or your own converter).
Comparing a naive datetime with an aware one...
Show the answer
Raises TypeError. Python refuses to guess which zone the naive one is in.
Practise this
Problems that use this, graded on hidden tests
- Reformat Date StringsData wrangling Easy
- CSV Rows to Typed RecordsData wrangling Easy
- A Re-iterable Date RangeGenerators & iterators Medium
Keep going
Up next · new module: Built-in data structures · 7 min readLists, dicts and sets: what each operation costs
Pick the container from the question, and why a set turns an hour-long loop into a second.
Related lessons
Strings and built-in functionsPython for data engineers · 6 min read
Generators and lazy evaluationPython for data engineers · 5 min read
Exceptions and context managers
Previous: Strings and built-in functions