Sub topic 9
Edge cases: today, gaps and duplicates
The earlier chapters built check_in, current_streak, longest_streak and completion_rate. They work on a normal week. This chapter covers the inputs that break a tracker: a check-in logged twice, a day that isn't over yet, a missed day, and dates that arrive in the wrong shape.
This chapter assumes you know:
- Python sets, dictionaries and functions.
- The
date,datetimeandtimedeltatypes from the standard library. - The data model from earlier chapters: a dictionary mapping each habit name to a set of
dateobjects.
Why these cases need attention
A streak counter is easy to write for the happy path and easy to get wrong at the edges. Most bugs here don't crash. They return a plausible but wrong number. A streak of 0 at 9 a.m. on a day you haven't had time to log yet looks like a real result, and it discourages you for no reason.
The edge cases fall into three groups:
- Duplicates: the same day recorded more than once.
- Today: a day that is still in progress.
- Gaps: days with no check-in, including days that were never supposed to count, such as future dates.
Duplicates
The data model already handles the simplest duplicate. A set ignores a second add of the same value, so logging "read" twice on one day leaves one entry. No counter ever reaches 2 for a single day, which means the streak and completion rate can't be inflated by repeated check-ins.
The set only helps if the two values compare as equal, and that is where a subtle bug lives. A datetime is a subclass of date, but a datetime never equals a date, even on the same calendar day:
from datetime import date, datetime
print(datetime(2026, 11, 27, 8, 0) == date(2026, 11, 27)) # False
print(len({datetime(2026, 11, 27, 8, 0), date(2026, 11, 27)})) # 2If any code path stores datetime.now() instead of date.today(), the same day appears twice, and every later lookup such as today in days fails. Two datetime values on the same day with different times are also distinct set members. The fix is to normalize at the single entry point, check_in, so no other code needs to care:
from datetime import date, datetime
log = {}
def check_in(habit, day=None, today=None):
"""Record a check-in. Return True if it was new, False if it was a duplicate."""
today = today or date.today()
day = day or today
if isinstance(day, datetime): # test datetime first: it is also a date
day = day.date()
if day > today:
raise ValueError(f"cannot check in for a future date: {day}")
days = log.setdefault(habit, set())
is_new = day not in days
days.add(day)
return is_new
print(check_in("read", today=date(2026, 11, 27))) # True
print(check_in("read", today=date(2026, 11, 27))) # False
print(check_in("read", datetime(2026, 11, 27, 22, 15), today=date(2026, 11, 27))) # False
print(len(log["read"])) # 1Three decisions are in this function:
- Normalize to
date. Theisinstance(day, datetime)check comes first becausedatetimeis a subclass ofdate, so testing fordatefirst would match both. - Reject future dates. A check-in for tomorrow is almost always a typo, and it would inflate
longest_streak, which does not look at today's date. - Return whether the check-in was new. A command-line front end can use this to print "already logged today" instead of silently succeeding.
The today parameter is there for testing. A function that reads the clock internally can't be checked against a fixed date, so every function in this tracker accepts today as an optional argument.
Today is still in progress
At 8:57 a.m. you have not had the chance to read yet. A streak function that requires today to be logged would report 0 for a 40-day streak every morning. The version from the streak chapter avoids this by counting back from yesterday when today is missing:
day = today if today in days else today - timedelta(days=1)The rule is that an unlogged today is pending, not missed. A day only counts as missed once it is over, so the streak stays alive until midnight. The flowchart shows the full decision.
Two consequences are worth knowing:
- If today is not logged and yesterday is also missing, the streak is 0. The grace applies to one day only.
- The displayed streak can go down without you doing anything wrong. At 11:59 p.m. it may read 40, and at 12:01 a.m. it reads 0 if yesterday was never logged. That is the correct behavior, because the streak broke at midnight.
Gaps
A gap is any day without a check-in. Both streak functions treat a gap as the end of a run, but they use it differently:
current_streakstops at the first gap going backwards from today, so only the most recent run counts.longest_streakresets its run counter to 1 at every gap and keeps the best run it saw, so old runs still count.
A missed day therefore resets the current streak but never lowers the longest one. The two numbers answer different questions: "how am I doing now?" and "what have I managed before?"
The same reasoning applies to a gap in the middle of the data, such as a holiday week. Those days are simply absent from the set, and nothing needs to be stored for a missed day. Storing only the days that happened keeps the data model small and makes the "missing means missed" rule automatic.
Test the cases with a fixed date
The most reliable way to check these rules is a table of inputs and expected outputs, run against a fixed today. This script is complete and runs as shown:
from datetime import date, timedelta
def current_streak(days, today=None):
today = today or date.today()
day = today if today in days else today - timedelta(days=1)
streak = 0
while day in days:
streak += 1
day -= timedelta(days=1)
return streak
def longest_streak(days):
best = run = 0
previous = None
for day in sorted(days):
if previous is not None and day - previous == timedelta(days=1):
run += 1
else:
run = 1
best = max(best, run)
previous = day
return best
today = date(2026, 11, 27)
def back(n):
return today - timedelta(days=n)
# name: (days logged, expected current streak, expected longest streak)
cases = {
"empty": (set(), 0, 0),
"only today": ({today}, 1, 1),
"today pending": ({back(1), back(2), back(3)}, 3, 3),
"today done": ({today, back(1), back(2), back(3)}, 4, 4),
"missed yesterday": ({today, back(2), back(3)}, 1, 2),
"stale": ({back(2), back(3)}, 0, 2),
"future entry": ({today, back(-1)}, 1, 2),
}
for name, (days, cur, lon) in cases.items():
assert current_streak(days, today) == cur, name
assert longest_streak(days) == lon, name
print("ok", name)The last case is deliberate. A future date in the set doesn't affect current_streak, which walks backwards from today, but longest_streak counts it and reports 2. That inconsistency is why check_in rejects future dates, and why data loaded from a hand-edited JSON file deserves the same check.
| Case | Current streak | Longest streak | Why |
|---|---|---|---|
| Empty log | 0 | 0 | The loops never run. |
| Today pending, 3 days before | 3 | 3 | Counting starts at yesterday. |
| Missed yesterday, today done | 1 | 2 | The gap ends the current run only. |
| Last check-in two days ago | 0 | 2 | Both today and yesterday are missing. |
| Future date in the log | 1 | 2 | Only the longest streak sees it. |
Dates and the clock
Some problems come from how "today" is defined rather than from the data.
Midnight is a hard boundary. date.today() uses the computer's local clock. If you read at 12:30 a.m. before bed, that check-in belongs to the new day, which can break a streak you meant to extend. A common remedy is to treat the day as ending at a later hour, such as 4 a.m.:
from datetime import datetime, timedelta
def logical_today(now=None, cutoff_hour=4):
now = now or datetime.now()
return (now - timedelta(hours=cutoff_hour)).date()
print(logical_today(datetime(2026, 11, 28, 1, 30))) # 2026-11-27
print(logical_today(datetime(2026, 11, 28, 9, 0))) # 2026-11-28You would pass this value as the today argument everywhere. It is a design choice, not a requirement, and it should be a visible setting so the numbers don't change unexpectedly.
Daylight saving time does not matter. The tracker only subtracts timedelta(days=1) from date objects, which is calendar arithmetic. A 23-hour or 25-hour day doesn't cause skipped or doubled days. The problem would only appear if you stored full timestamps and divided by 24 hours.
Travel across time zones changes what "today" means. A tracker that uses the local clock will accept two check-ins for what felt like one day, or none for a day that felt long. For a personal tracker, that is acceptable. If it matters, add a --date option to the command-line interface so you can say which day you mean.
Backfilling is legitimate. You may remember yesterday's check-in this morning. Allowing check_in to take a past date is correct, and the set absorbs it. It will also repair a broken streak, so decide whether you want that. A tracker that allows unlimited backfilling measures what you claim, not what you did.
The completion rate at the edges
completion_rate divides by a fixed window, which is wrong for a habit that began recently. A habit started 3 days ago, done every day, scores 3/30 = 0.1, though the real rate is 100%. This version shrinks the window to the days the habit has existed:
from datetime import date, timedelta
def completion_rate_since_start(days, end, window=30):
if not days:
return 0.0
first = min(days)
length = min(window, (end - first).days + 1)
if length < 1:
return 0.0
start = end - timedelta(days=length - 1)
done = sum(1 for d in days if start <= d <= end)
return done / length
today = date(2026, 11, 27)
days = {today - timedelta(days=2), today}
print(round(completion_rate_since_start(days, today), 2)) # 0.67Two days out of the three since the first check-in gives 0.67. Treating the first check-in as the start date is an assumption. If you define the start date separately, store it with the habit and use it instead of min(days).
Whichever version you use, the same rule about today applies: if the window ends on today and today is still pending, the rate is lowered by a day that hasn't finished. Passing yesterday as end in the morning avoids this.
Persistence and duplicates
The JSON file stores dates as sorted ISO strings, and loading rebuilds them into a set. If someone edits the file and adds the same date twice, the set absorbs it on load. If someone adds an invalid string such as "2026-13-01", date.fromisoformat raises ValueError. Letting that error surface is better than skipping the entry silently, because a quiet skip would shorten a streak without any explanation.
Summary of the rules
- Store only
dateobjects, converted atcheck_in. - A set makes duplicates harmless, but only for values that compare as equal.
- An unlogged today is pending, and an unlogged yesterday is a break.
- A gap ends the current streak and never lowers the longest streak.
- Reject future dates, and surface bad dates when loading.
- Shrink the completion window for new habits.
Exercise
A habit has check-ins on 2026-11-20, 2026-11-21 and 2026-11-23. Today is 2026-11-24 and nothing has been logged yet. What do currentstreak and longeststreak return, and what do they return at the start of 2026-11-25 if nothing is logged on the 24th?
Show answer
On the 24th, currentstreak starts at yesterday (the 23rd), which is logged, then finds the 22nd missing, so it returns 1. longeststreak returns 2 (the 20th and 21st). On the 25th, today is not logged and yesterday (the 24th) is not logged either, so currentstreak returns 0. longeststreak is still 2.
Exercise
A user adds the check-in datetime(2026, 11, 27, 21, 0) directly to the set, without using checkin, and the set already contains date(2026, 11, 27). Why does currentstreak still work for that day, and why is the data still wrong?
Show answer
currentstreak tests membership with the plain date, which is already in the set, so the streak is correct for that day. The data is still wrong because the set now holds two entries for one day. longeststreak sorts the set and compares datetime with date, which raises a TypeError because the two types can't be ordered against each other. Normalizing to date in check_in prevents both problems.
Exercise
Change logical_today so that the day ends at 3 a.m. instead of 4 a.m. What does it return for datetime(2026, 11, 28, 3, 30)?
Show answer
Call it with cutoff_hour=3. Subtracting 3 hours from 03:30 on the 28th gives 00:30 on the 28th, so the function returns date(2026, 11, 28). At 02:59 the result would still be the 27th.