Sub topic 2
Modeling check-ins as dates
This chapter covers the data model the rest of the tracker rests on. It assumes you know basic Python (functions, dictionaries, sets, loops) and the date and timedelta types from the datetime module. By the end you will be able to explain why each habit's check-ins are stored as a set of calendar dates, and you will have a working structure to build on.
The question the model must answer
Every number the tracker produces comes from one question: on which days was this habit done? The current streak, the longest streak and the completion rate are all calculations over the answer. The choice of data structure decides how easy and how reliable those calculations are.
A habit tracker records a yes/no fact per habit per day. Either you read today or you did not. The earlier chapter on defining a trackable habit gave you a clear yes/no test, so the model only needs to store the days on which the answer was yes.
Candidate structures
Several structures could hold this information. Compare them on the operations the tracker needs: add a check-in, test whether a day is logged, and iterate over logged days.
| Structure | Duplicate check-ins | "Was day X logged?" | Ordering | Main drawback |
|---|---|---|---|---|
| List of dates | Stored twice unless you check first | Scans the whole list | Insertion order | Duplicates inflate counts |
| List of timestamps | Same-day entries look different | Needs date extraction | Insertion order | Time of day is noise |
| Dictionary of date to boolean | Overwrites the same key | Constant time | Insertion order | Storing `False` adds nothing |
| Set of dates | Ignored automatically | Constant time | None | You must sort when order matters |
The set wins for this job. Membership tests are fast, and adding a date that is already present changes nothing. The missing order is a small cost, because the one calculation that needs order (the longest streak) can sort the dates first.
Why dates, not timestamps
A datetime carries a time of day. If you stored datetime.now() for each check-in, two check-ins on the same day would be different values, and the set would keep both. You would then have to strip the time before every comparison.
The date type holds only year, month and day. Two check-ins on the same calendar day produce equal date objects, which hash to the same value, so a set treats them as one element.
from datetime import date, datetime
a = datetime(2026, 11, 27, 7, 30)
b = datetime(2026, 11, 27, 21, 5)
print(len({a, b})) # 2: different timestamps
print(len({a.date(), b.date()})) # 1: same calendar dayThe habit is "done or not done today", so the time of day carries no information for this tracker. Dropping it up front removes a whole class of bugs.
The structure: a dictionary of sets
One habit needs one set of dates. A tracker with several habits needs one set per habit. A dictionary maps each habit name to its set.
from datetime import date
log = {
"read": {date(2026, 11, 25), date(2026, 11, 26), date(2026, 11, 27)},
"stretch": {date(2026, 11, 20), date(2026, 11, 27)},
}The type is dict[str, set[date]]. The key is the habit name and the value is the set of days on which it was done. This is the only state the tracker keeps. Everything else is computed from it.
The diagram below shows how the pieces relate.
Recording a check-in
Adding a check-in means finding the habit's set and adding a date to it. The first time you see a habit, its set does not exist yet. dict.setdefault creates an empty set on first use and returns the existing one afterwards.
from datetime import date
log = {} # habit name -> set of dates on which it was done
def check_in(habit, day=None):
day = day or date.today()
log.setdefault(habit, set()).add(day)
check_in("read")
check_in("read") # a duplicate check-in on the same day changes nothing
print(len(log["read"])) # 1Three details are worth noting.
day=Nonewithday or date.today()lets callers omit the date for the usual case, "I did it today", while still allowing a specific date. That is useful for tests and for logging a day you forgot.set.addis idempotent. Calling it twice with equal values leaves one element. The function needs noif day not in ...guard.- The function mutates the module-level
log. That is fine for a small script. Later chapters pass the log around explicitly where it helps testing.
Idempotence is a feature
Idempotent means that doing an operation twice has the same effect as doing it once. This matters because users run commands twice. They press the up arrow and Enter, a script retries after an error, or they check in from two devices. With a set, none of these corrupt the count.
With a list, the same sequence would give len(log["read"]) == 2 for one day of reading, and every metric downstream would be wrong. The set removes the need to remember to deduplicate.
Using the structure
Because the log is plain Python collections, the common questions are one-liners.
from datetime import date
log = {
"read": {date(2026, 11, 25), date(2026, 11, 26), date(2026, 11, 27)},
"stretch": {date(2026, 11, 20), date(2026, 11, 27)},
}
today = date(2026, 11, 27)
print(today in log["read"]) # True: was it done today?
print(len(log["stretch"])) # 2: total days done
print(sorted(log["read"])[-1]) # 2026-11-27: most recent day
print(log["read"] & log["stretch"]) # days both habits were done
print(sorted(log["read"] - log["stretch"])) # days read but not stretchedThe set operators & (intersection) and - (difference) come for free. You will not need them in the core tracker, but they show what the model gives you cheaply.
Reading a habit that does not exist
log["meditate"] raises KeyError if that habit has never been logged. Choose a policy and apply it consistently. Two reasonable options:
- Use
log.get(habit, set())when reading, so an unknown habit looks like a habit with no check-ins. - Treat an unknown habit as an error and report it to the user.
The tracker uses the first option for display, because a new habit with zero check-ins is a normal state, not a mistake.
from datetime import date
log = {"read": {date(2026, 11, 27)}}
days = log.get("meditate", set())
print(len(days)) # 0Note that get does not insert the key, so reading never changes the log. setdefault does insert, so use it only when writing.
Common errors
The following mistakes come up often when building this model.
- Storing
datetimeinstead ofdate. Same-day check-ins stop deduplicating. Convert with.date()at the boundary where a timestamp enters the program. - Storing dates as strings in memory.
"2026-11-27"is easy to save but cannot be subtracted or compared by day count. Keep realdateobjects in memory and convert to strings only when saving. The persistence chapter covers this. - Using a shared default set. Writing
log = defaultdict(set)is fine. Writing a function with a default argument likedef f(days=set())is not, because the one set is shared between all calls. - Assuming a set has an order. Iterating a set gives no guaranteed order. Call
sorted()before any logic that depends on sequence. - Mutating a set while looping over it. Adding or removing elements during iteration raises
RuntimeError. Loop oversorted(days)or a copy.
from datetime import date
days = {date(2026, 11, 25), date(2026, 11, 26)}
for d in sorted(days): # sorted() returns a new list, so this is safe
days.add(date(2026, 11, 27))
print(len(days)) # 3Time zones and the meaning of "today"
date.today() uses the computer's local date. A person who checks in at 23:50 and again at 00:10 has logged two different calendar days, and the model records exactly that. This is usually what you want, because a habit belongs to the user's own day.
Problems appear if the computer's clock and the user's day disagree, for example a server in another time zone. For a personal command-line tool running on your own machine, local time is correct. Chapter 9 returns to this under date edge cases.
What the model does not capture
Every model leaves something out. This one cannot represent:
- How many times you did the habit in a day (it is yes/no only).
- How long or how well you did it.
- A day you deliberately skipped, such as sick leave, as different from a day you forgot.
These limits are deliberate. They match the yes/no definition of a trackable habit and keep the later calculations short. If you later need counts, a dict[date, int] per habit is the natural extension, at the cost of more complex streak logic.
Summary of the model
- State is
dict[str, set[date]], mapping a habit name to the days it was done. - Use
date, notdatetime, so one calendar day is one element. - Sets ignore duplicates and test membership in constant time.
- Sort the dates when order matters.
- Missing days are absent, not stored as
False.
The next chapters build on this structure. The streak calculations walk the set one day at a time using today in days, and the completion rate counts members of the set inside a date range.
Exercise
A teammate changes check_in to store datetime.now() instead of date.today(), and the unit test that calls check_in("read") twice and expects len(log["read"]) == 1 starts failing. Explain why it fails and give the one-line fix at the point where the value is stored.
Show answer
Two calls to datetime.now() return different timestamps because they differ in time of day, even on the same calendar day. The set treats them as distinct elements, so the length is 2. The fix is to keep only the calendar day, for example log.setdefault(habit, set()).add(day.date()) when day is a datetime, or simply to use date.today(). Equal date objects hash equally, so the set deduplicates them again.
Exercise
Given log = {"read": {date(2026, 11, 25), date(2026, 11, 27)}}, write an expression that returns the number of days in the log that are on or after date(2026, 11, 26), and say what it returns. Then say what log["run"] does and what to use instead to treat an unknown habit as empty.
Show answer
sum(1 for d in log["read"] if d >= date(2026, 11, 26)) returns 1, because only 2026-11-27 qualifies. log["run"] raises KeyError because that habit was never logged. Use log.get("run", set()), which returns an empty set without adding the key to the log.