Sub topic 4
Calculating the current streak
A streak is the number of consecutive days a habit has been done, ending now. It is the number most people look at first in a habit tracker, and it is easy to get subtly wrong. This chapter builds current_streak, explains why it counts back from a particular day, and covers the errors that show up most often.
Prerequisites
This chapter assumes you know the following:
- Basic Python: functions, loops, sets and dictionaries.
- The
datetimemodule'sdateandtimedeltatypes. - The data model from earlier chapters: each habit maps to a set of
dateobjects, one per day it was done.
If you want a refresher, the earlier chapters on modeling check-ins and recording a check-in cover the last point.
What "current" means
A habit's log is a set of dates. The current streak is the length of the unbroken run of consecutive dates that ends at the present moment. Three terms need to be pinned down.
- Consecutive means each date is exactly one calendar day after the previous one. There are no gaps.
- Ending now means the run must reach today, or yesterday if today is not logged yet.
- Streak length is the count of dates in that run.
Suppose today is 2026-11-27 and the log holds these dates:
| Logged dates | Today logged? | Current streak |
|---|---|---|
| Nov 25, 26, 27 | Yes | 3 |
| Nov 24, 25, 26 | No | 3 |
| Nov 24, 25 | No | 0 |
| Nov 20, 21, 22 | No | 0 |
| (empty) | No | 0 |
The second row is the important one. The user has not checked in yet today, but the day is not over. The streak should still read 3, not 0. The third row is different: yesterday is missing, so the run has already been broken and the streak is 0.
The algorithm
The approach is to walk backwards one day at a time and count how many days are in the set.
- Choose a starting day: today if it is logged, otherwise yesterday.
- While the day under inspection is in the set, add one to the count and step back one day.
- Stop at the first day that is not in the set and return the count.
from datetime import date, timedelta
def current_streak(days, today=None):
today = today or date.today()
# If today is not logged yet, count back from yesterday so the streak is not lost mid-day.
day = today if today in days else today - timedelta(days=1)
streak = 0
while day in days:
streak += 1
day -= timedelta(days=1)
return streakThe function takes the set of dates and an optional today. Passing today explicitly is not a convenience feature. It makes the function testable, because a test can pin the date instead of depending on the clock.
The diagram below shows the decision and the loop.
Running it on real data
Here is the function run against the table above. The dates are fixed, so the output is the same on every run.
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
today = date(2026, 11, 27)
cases = {
"logged today": {date(2026, 11, 25), date(2026, 11, 26), date(2026, 11, 27)},
"not yet today": {date(2026, 11, 24), date(2026, 11, 25), date(2026, 11, 26)},
"missed yesterday": {date(2026, 11, 24), date(2026, 11, 25)},
"old run": {date(2026, 11, 20), date(2026, 11, 21), date(2026, 11, 22)},
"empty": set(),
}
for name, days in cases.items():
print(f"{name}: {current_streak(days, today)}")The output is:
logged today: 3
not yet today: 3
missed yesterday: 0
old run: 0
empty: 0Why a set makes this simple
Because the log is a set, the test day in days is a constant-time lookup on average, and the loop does one lookup per day of the streak. A streak of 365 days costs 366 lookups, regardless of how many other dates are in the log.
Sets also remove two problems before they start:
- Duplicates. Two check-ins on the same day are stored once, so they cannot inflate the streak. A list of dates would count the same day twice, and the walk-back logic would not notice, but any code that used
len(list)would. - Order. The walk does not need sorted data. Lookups work whatever order the dates were added in, so a user who back-fills an old day does not break anything.
A list-based design would need to sort and de-duplicate before computing a streak. That is the main reason the data model uses a set.
Common errors
Counting from today only
The most common mistake is to start at today unconditionally:
from datetime import date, timedelta
def current_streak_naive(days, today=None):
day = today or date.today()
streak = 0
while day in days:
streak += 1
day -= timedelta(days=1)
return streakThis returns 0 every morning until the user checks in, even with a 100-day run behind them. The streak appears to reset at midnight and come back when the user logs. That is confusing and discourages people. The yesterday fallback fixes it.
Treating a missed yesterday as still alive
The opposite mistake is to be too forgiving, for example by starting at the most recent logged date regardless of how old it is:
from datetime import date, timedelta
def current_streak_wrong(days):
day = max(days) if days else None
streak = 0
while day in days:
streak += 1
day -= timedelta(days=1)
return streakIf the last check-in was two weeks ago, this function reports the length of that old run as if it were current. A current streak must be anchored to today or yesterday. Anything older is a broken streak and the answer is 0.
Using datetimes instead of dates
If the log stores datetime objects, every check-in has a time of day, and day in days fails because 2026-11-27 09:00 is not equal to 2026-11-27 00:00. Store date objects and convert with .date() at the point of input. Mixing the two types in one set is a related error: Python does not raise one, but the comparisons silently fail. Note that datetime is a subclass of date, which is why the mix is accepted without complaint.
from datetime import date, datetime
d = date(2026, 11, 27)
dt = datetime(2026, 11, 27, 9, 0)
print(dt == d) # False
print(dt.date() == d) # TrueMutating the loop variable's source
The function modifies only the local day, which is an immutable date, so the log is never changed. If you extend the function, keep it that way. A streak calculation should read the log and never write to it.
Time zones and the definition of "today"
date.today() returns the date in the machine's local time zone. For a personal tracker that is almost always what you want: the user's day ends at their own midnight. Two situations deserve attention.
- Travel. If the user flies across time zones, the local date can jump forward or back. A trip west can make "today" the same date for longer, and a trip east can skip a date. The tracker does not adjust for this, and the streak follows the clock on the device.
- Late-night habits. Someone who works until 2 a.m. may think of 1 a.m. Saturday as still being Friday. The simple model records it as Saturday. If this matters to you, shift the day boundary by subtracting a few hours before taking the date:
from datetime import datetime, timedelta
def logical_today(day_starts_at_hour=4):
"""Treat the hours before day_starts_at_hour as the previous day."""
return (datetime.now() - timedelta(hours=day_starts_at_hour)).date()Pass the result as the today argument and the streak logic needs no change. Use the same function when recording a check-in, or the two will disagree about which day a check-in belongs to.
Testing the function
Because today is a parameter, the edge cases from the table become short tests. Each one runs without the system clock.
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 run(n, today):
"""Return a set of n consecutive dates ending on `today`."""
return {today - timedelta(days=i) for i in range(n)}
today = date(2026, 11, 27)
assert current_streak(set(), today) == 0
assert current_streak(run(5, today), today) == 5
assert current_streak(run(5, today - timedelta(days=1)), today) == 5
assert current_streak(run(5, today - timedelta(days=2)), today) == 0
assert current_streak(run(5, today) | run(3, today - timedelta(days=7)), today) == 5
# Month and year boundaries need no special handling.
new_year = date(2027, 1, 2)
assert current_streak(run(4, new_year), new_year) == 4
print("all checks passed")The last two checks are worth noting. A second, older run does not add to the current one, because the loop stops at the first gap. A run that crosses a month or year boundary also works with no extra code, because timedelta arithmetic on date objects handles the calendar for you. Do not try to compute streaks by subtracting day.day values. That breaks at the end of every month.
Limits of this definition
The function answers one question: how many days in a row, counting back from now? It does not tell you how good the habit is. A user who did the habit 29 days out of 30 and missed yesterday sees a streak of 0. That is accurate for a streak, but it hides the pattern. Later chapters add the longest streak and the completion rate over a window, and the two together give a fairer picture than the current streak alone.
There is also a design choice about grace. Some trackers allow one skipped day without resetting the streak. This chapter does not, because the rule "every day counts" is simple, testable and matches the yes/no check-in defined earlier. If you add grace days, put the rule in its own function so that the basic definition stays intact.
Key points
- The current streak is the run of consecutive logged days ending today, or ending yesterday if today is not yet logged.
- Walking backwards with a set lookup is simple and does not need the dates to be sorted.
- Pass
todayas a parameter so tests do not depend on the clock. - Store
dateobjects, notdatetimeobjects, and use one definition of "today" throughout. - A streak anchored to anything older than yesterday is broken, and the answer is 0.
Exercise
A habit's log contains the dates Nov 20, 21, 22, 23 and 25. Today is Nov 26 and today has not been logged. What does current_streak return, and why? What does it return if the user then logs Nov 26?
Show answer
It returns 1 before logging. Today (Nov 26) is not in the set, so counting starts from yesterday, Nov 25, which is logged. Nov 24 is not logged, so the walk stops after one day. After the user logs Nov 26, counting starts from today. Nov 26 and Nov 25 are both logged and Nov 24 is not, so the result is 2. The earlier run of Nov 20 to 23 does not count, because the gap on Nov 24 breaks the streak.
Exercise
A teammate changes the first lines of current_streak so that day always starts at today, with no yesterday fallback. Describe one input where the result is wrong and what the user would see.
Show answer
Take any log with a long run ending yesterday, for example Nov 1 to Nov 26, evaluated on Nov 27 before the user checks in. The changed function sees that Nov 27 is not in the set and returns 0. The user would see their streak drop to 0 every morning and return to 27 only after they check in, even though they have not missed a day.
Exercise
Write a test, using the run helper from the testing section, that checks a streak across a leap day. Use today = date(2028, 3, 1) and a run of 3 days ending on that date. What value should current_streak return, and which dates does the run contain?
Show answer
The run contains Feb 28, Feb 29 and Mar 1, 2028, because 2028 is a leap year. The test is assert current_streak(run(3, date(2028, 3, 1)), date(2028, 3, 1)) == 3. It passes because timedelta arithmetic on date objects knows the calendar, so no special leap-year code is needed.