A wellness tracker can be small, useful, and respectful of its user's privacy. It does not need an account system, a cloud database, an advertising SDK, or a chart that turns a missed day into a failure. In fact, those features often make the first version harder to maintain and less trustworthy.
In this tutorial, we will build a local-first habit tracker using Python's standard library and SQLite. The goal is not to measure anyone's health or offer medical advice. It is to record simple choices—such as taking a screen break or stretching for a few minutes—and produce an understandable weekly summary.
We will cover data modeling, calendar boundaries, idempotent writes, input validation, and the limits of local storage. The complete runnable program is included below, followed by sample commands and tests you can adapt.
- Define the smallest useful product The first version needs only four operations: create a named habit, mark a particular day as completed, undo an accidental check-in, and summarize a seven-day window. Users can choose a weekly target between one and seven days. We intentionally record whether the action was completed, not a medical measurement or a detailed personal diary.
That distinction matters. A feature that only needs to know whether someone took a break should not ask for age, location, weight, medication, or biometric measurements. Data minimization reduces the impact of mistakes and makes the interface easier to explain.
Our example habits will be "Stretch for five minutes" and "Take a screen break." They are labels supplied by the user, not built-in recommendations or treatment plans.
- Use a relational model instead of a pile of JSON files SQLite is a good match for a single-device prototype. It ships with Python through sqlite3, supports transactions, and lets us define uniqueness and foreign-key constraints without deploying a database server.
We need two tables:
- habits stores a unique label and an achievable weekly target.
- checkins stores one completion record per habit per calendar day. The composite primary key (habit_id, day) is central to the design. Clicking "complete" twice should not double someone's progress. The constraint prevents duplicate rows even when a caller forgets to check first.
We store dates as ISO strings (YYYY-MM-DD). For normalized calendar dates, lexical order matches chronological order, making bounded date queries straightforward. Date strings should still be validated in Python: SQLite's TEXT column does not guarantee that 2026-02-30 is a real date.
- Make the write operation idempotent Idempotency means that applying the same action twice has the same lasting effect as applying it once. This is especially important for mobile interfaces, where a user might tap twice or retry after a delayed response.
The tracker uses a parameterized INSERT OR IGNORE operation. The database either creates the check-in or retains the existing one. It does not increment an arbitrary counter. We also verify that the habit exists, so an unknown label is not mistaken for a successful update.
For corrections, a dedicated undo command deletes a record for a specific habit and date. That is safer than changing the meaning of a previous event in place and easier to communicate in the interface.
- Decide what “this week” actually means Weekly reporting has a surprisingly subtle product question: does a week mean Monday through Sunday, or the last seven calendar dates? Both are valid, but they answer different questions.
For this prototype, the window is the specified end date plus the preceding six calendar days, inclusive. For example, a report ending on November 26 includes November 20 through November 26. That rule is explicit in the output so the user can compare results consistently.
The SQL query starts with every habit and left-joins only check-ins inside the selected window. A habit with zero check-ins must still appear with a count of zero; otherwise the dashboard silently hides the habits that may need attention.
The report compares a count with a target, but it does not turn that number into a medical score. It is a planning signal, not a clinical assessment.
- Keep date handling predictable date.today() is useful as a command-line default, but it uses the computer's local calendar. Travel, daylight-saving transitions, and devices set to the wrong time zone can make “today” ambiguous. That is why every check-in also supports an explicit --day argument.
For a future multi-device system, choose a user's home time zone and define how late check-ins are handled. A timestamp in UTC alone does not tell you which local calendar date the user intended to mark. That decision belongs in the product specification, not as an accidental side effect of a date library.
We do not need timestamps for every action in the current product. Adding fields merely because they are available increases the data retained without necessarily improving the experience.
- Complete Python implementation Save the following program as wellness_tracker.py. It uses no external packages and makes no network requests. The --db option lets you choose where the local SQLite file lives. import argparse import sqlite3 from datetime import date, timedelta from pathlib import Path
SCHEMA = """
CREATE TABLE IF NOT EXISTS habits (
id INTEGER PRIMARY KEY,
label TEXT NOT NULL UNIQUE,
target_per_week INTEGER NOT NULL CHECK(target_per_week BETWEEN 1 AND 7)
);
CREATE TABLE IF NOT EXISTS checkins (
habit_id INTEGER NOT NULL REFERENCES habits(id) ON DELETE CASCADE,
day TEXT NOT NULL,
PRIMARY KEY (habit_id, day)
);
"""
def open_db(path):
path = Path(path).expanduser()
path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(path)
conn.execute("PRAGMA foreign_keys = ON")
conn.executescript(SCHEMA)
return conn
def parse_day(value):
parsed = date.fromisoformat(value)
if parsed.isoformat() != value:
raise ValueError("Use an ISO date such as 2026-11-26")
return value
def add_habit(conn, label, target):
label = label.strip()
if not label:
raise ValueError("Habit label cannot be empty")
if not 1 <= target <= 7:
raise ValueError("Weekly target must be between 1 and 7")
with conn:
conn.execute(
"INSERT INTO habits(label, target_per_week) VALUES (?, ?)",
(label, target),
)
def check_in(conn, label, day):
parse_day(day)
with conn:
cur = conn.execute(
"""INSERT OR IGNORE INTO checkins(habit_id, day)
SELECT id, ? FROM habits WHERE label = ?""",
(day, label),
)
if not conn.execute("SELECT 1 FROM habits WHERE label = ?", (label,)).fetchone():
raise ValueError(f"Unknown habit: {label}")
return cur.rowcount == 1
def undo_check_in(conn, label, day):
parse_day(day)
with conn:
cur = conn.execute(
"""DELETE FROM checkins WHERE day = ?
AND habit_id = (SELECT id FROM habits WHERE label = ?)""",
(day, label),
)
return cur.rowcount == 1
def weekly_report(conn, ending):
end = date.fromisoformat(parse_day(ending))
start = end - timedelta(days=6)
rows = conn.execute(
"""SELECT h.label, h.target_per_week, COUNT(c.day) AS completed_days
FROM habits AS h
LEFT JOIN checkins AS c ON c.habit_id = h.id
AND c.day BETWEEN ? AND ?
GROUP BY h.id
ORDER BY h.label""",
(start.isoformat(), end.isoformat()),
).fetchall()
return start.isoformat(), ending, rows
def main():
parser = argparse.ArgumentParser(description="Local wellness habit tracker")
parser.add_argument("--db", default="wellness.db", help="SQLite file path")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", help="Create a weekly habit") add.add_argument("label") add.add_argument("--target", type=int, default=3) check = sub.add_parser("check", help="Mark a day complete (idempotent)") check.add_argument("label") check.add_argument("--day", default=date.today().isoformat()) undo = sub.add_parser("undo", help="Remove an accidental check-in") undo.add_argument("label") undo.add_argument("--day", default=date.today().isoformat()) report = sub.add_parser("report", help="Summarize the last seven calendar days") report.add_argument("--ending", default=date.today().isoformat()) args = parser.parse_args() try: with open_db(args.db) as conn: if args.command == "add": add_habit(conn, args.label, args.target) print(f"Added: {args.label}") elif args.command == "check": new = check_in(conn, args.label, args.day) print("Recorded" if new else "Already recorded") elif args.command == "undo": removed = undo_check_in(conn, args.label, args.day) print("Removed" if removed else "Nothing to remove") elif args.command == "report": start, end, rows = weekly_report(conn, args.ending) print(f"Window: {start} to {end} (inclusive)") for label, target, count in rows: print(f"{label}: {count}/{target} days (weekly target)") except (ValueError, sqlite3.Error) as exc: parser.error(str(exc)) if name == "main":
main()
- Run the tracker locally From a terminal in the same directory, create a habit and record a day: python wellness_tracker.py --db wellness.db add "Stretch for five minutes" --target 4 python wellness_tracker.py --db wellness.db add "Take a screen break" --target 5 python wellness_tracker.py --db wellness.db check "Stretch for five minutes" --day 2026-11-26 python wellness_tracker.py --db wellness.db check "Take a screen break" --day 2026-11-25 python wellness_tracker.py --db wellness.db report --ending 2026-11-26 The report will show the seven-day date range and each habit's completed days against its weekly target. If you run the same check command again, the program prints Already recorded instead of adding another row. If you entered a day by mistake, use undo with the same label and date.
Notice that none of these commands requires an email address or a web account. A fully local application cannot upload records by accident unless you later introduce code that does so.
- Test the rules, not just the happy path A useful automated test creates a temporary database, registers a habit, records the same date twice, and confirms that the weekly count remains one. Then it checks that an invalid calendar date is rejected, a missing habit does not create an orphan record, and undoing a check-in changes the report.
The most valuable assertions for this application are about invariants:
- There is at most one check-in for each (habit, date) pair.
- The weekly report covers exactly seven dates, including both boundaries.
- A habit with no activity still appears in a report.
- An invalid date or target cannot quietly enter the database.
- Repeating a correction does not delete unrelated activity. For example, the essential idempotency assertion can be written using an in-memory or temporary SQLite database: assert check_in(conn, "Stretch for five minutes", "2026-11-26") is True assert check_in(conn, "Stretch for five minutes", "2026-11-26") is False assert weekly_report(conn, "2026-11-26")[2][0][2] == 1 Use a test-only database, not the file containing someone's actual records.
- Privacy-first does not automatically mean secure Local-first removes a category of server-side exposure, but it does not encrypt the SQLite file. Anyone with access to an unlocked or compromised device may be able to read it. Backups can also copy the file to cloud storage if a user has enabled device-wide backup.
A production application should explain where records are stored, offer export and deletion controls, define a retention policy, and consider operating-system key storage or database encryption when the sensitivity of the information warrants it. Do not imply that a standard SQLite database is encrypted just because no server is involved.
Avoid gathering symptom descriptions, diagnoses, or medication details for a simple habit checklist. If you build a more sensitive health application, privacy, consent, accessibility, and medical-device considerations require a separate, more rigorous design.
- Design feedback that supports autonomy A humane tracker should show progress without punishing irregular schedules. An app can report "three of four planned days" without announcing that the user has failed. It should also make it easy to change a weekly target or stop tracking an activity entirely.
For Persian-language readers interested in health awareness, nutrition, and practical everyday wellbeing, Salemio provides a related health and healthy-living perspective. The link is included for readers seeking that broader context; the sample code here remains a self-contained programming tutorial.
The architecture can grow later: add accessible reminders, optional local notifications, a user-controlled export, or charts that clearly explain their date range. But keep the same core rule: collect the least data necessary to deliver the promised feature.
- Where to go next For the next iteration, separate the SQLite layer from a UI layer so you can reuse it in a desktop application or a local web interface. Document the report window and the behavior of repeated taps as part of your API contract. If you eventually enable synchronization, introduce a conflict-resolution policy before shipping it, rather than assuming that two devices will always agree.
The broader engineering lesson is simple: trustworthy personal software starts with explicit data boundaries, predictable state changes, and clear explanations. A small habit tracker is a useful place to practice all three.
Disclosure: This tutorial was drafted with AI assistance. The example implementation was executed and tested using local, synthetic data. It is educational software, not a medical tool. Salemio is part of the publishing network associated with this article.