Sub topic 14
Putting the Three Modules Together
This chapter combines math, random, and datetime in small programs. It assumes you know the individual pieces from earlier chapters: math.isclose and math.fsum, random.Random instances, timedelta arithmetic, and the difference between naive and aware datetimes.
Why combine the modules
Each module answers one question. random decides which values to use, datetime gives those values meaning as calendar dates and times, and math summarizes the results. Real tasks usually need all three, for example:
- Generating test data with realistic dates.
- Simulating events over a year.
- Scheduling sample slots across time zones.
Most bugs come from the seams between the modules. A randrange bound can be off by one day, a float average can be compared with ==, or a naive datetime can meet an aware one. The examples below are built around those seams.
Pass the generator in
The global functions such as random.randint share one hidden generator for the whole process. If your function uses them, you can't control its output from a test. Create a random.Random instance and pass it in as a parameter. The caller then chooses between a fixed seed for tests and an unseeded generator for production.
import random
from datetime import date, timedelta
def random_date(rng: random.Random, start: date, end: date) -> date:
"""Return a date from start to end, both included."""
if end < start:
raise ValueError("end must not be before start")
span = (end - start).days + 1
return start + timedelta(days=rng.randrange(span))
rng_a = random.Random(2026)
rng_b = random.Random(2026)
window = (date(2026, 1, 1), date(2026, 12, 31))
first = random_date(rng_a, *window)
second = random_date(rng_b, *window)
print(first == second) # True: same seed, same call sequence
print(first.year) # 2026The + 1 matters. (end - start).days is the number of days between the two dates, so the January 1 to December 31 window gives 364. randrange(364) returns 0 to 363 and never reaches December 31. Adding 1 turns the distance into a count of dates, so randrange(span) can return every date in the window.
The two generators agree only if they receive the same sequence of calls. If one of them draws an extra number first, their streams drift apart. Keep one generator per independent concern, and don't share a single generator across unrelated code.
Distinct random dates and their spacing
random.sample never repeats an item. Sampling from range(365) picks distinct day offsets, and you never have to build a list of 365 dates. The next program turns the offsets into dates, sorts them, and measures the gaps with math.
import math
import random
from datetime import date, timedelta
def spread_report(days: list[date]) -> dict:
"""Summarize gaps (in days) between consecutive dates."""
if len(days) < 2:
raise ValueError("need at least two dates")
ordered = sorted(days)
gaps = [(later - earlier).days for earlier, later in zip(ordered, ordered[1:])]
mean = math.fsum(gaps) / len(gaps)
variance = math.fsum((g - mean) ** 2 for g in gaps) / len(gaps)
return {
"first": ordered[0],
"last": ordered[-1],
"mean_gap": mean,
"std_gap": math.sqrt(variance),
}
rng = random.Random(42)
start = date(2026, 1, 1)
offsets = rng.sample(range(365), k=6)
days = [start + timedelta(days=o) for o in offsets]
report = spread_report(days)
total_days = (report["last"] - report["first"]).days
print(len(set(days))) # 6: all distinct
print(math.isclose(report["mean_gap"] * 5, total_days)) # TrueSeveral details here reflect earlier chapters:
sorted(days)works becausedateobjects support comparison.- Subtracting two dates gives a
timedelta. Its.daysattribute is an integer. math.fsumadds the floats with less accumulated error thansum. Here the gaps are integers, but the squared deviations are not.- The final check multiplies the mean by 5 (the number of gaps) and compares it with the total span. That product may differ from the integer by a tiny rounding error, so the check uses
math.iscloseinstead of==. sampleraisesValueErrorifkis larger than the population. Validatekfirst if it comes from user input.
Weighted choices on a calendar
Use choices when repeats are allowed and some outcomes should be more likely. This example simulates which weekday a support ticket arrives on. It uses the weekday name from a date and counts the results.
import random
from collections import Counter
from datetime import date, timedelta
rng = random.Random(7)
monday = date(2026, 11, 23)
days = [monday + timedelta(days=i) for i in range(7)]
weights = [5, 5, 5, 5, 5, 1, 1] # weekdays busy, weekend quiet
arrivals = rng.choices(days, weights=weights, k=1000)
counts = Counter(d.strftime("%A") for d in arrivals)
print(sum(counts.values())) # 1000
print(set(counts) <= {d.strftime("%A") for d in days}) # TrueThe exact counts depend on the seed, so the checks above only assert properties that always hold. The same habit helps in tests. When a result is random, assert invariants such as a range, a count, or a relationship, and avoid asserting a specific random value unless the seed and Python version are pinned. Python does not promise that a seed produces the same sequence in every release for every method.
Random times in a specific time zone
Random timestamps raise the naive versus aware problem. The safe rule is to build aware datetimes at the edge, compute in UTC, and convert only for display. This function picks a random half-hour slot during business hours in a given zone and returns it in UTC.
import random
from datetime import date, datetime, timedelta, timezone
from zoneinfo import ZoneInfo
def random_slot(rng: random.Random, day: date, tz_name: str) -> datetime:
"""A random 30-minute slot start between 09:00 and 16:30 local time, as UTC."""
tz = ZoneInfo(tz_name)
minutes = rng.randrange(0, 8 * 60, 30) # 0, 30, ..., 450
local = datetime(day.year, day.month, day.day, 9, 0, tzinfo=tz)
local += timedelta(minutes=minutes)
return local.astimezone(timezone.utc)
rng = random.Random(11)
slot = random_slot(rng, date(2026, 11, 26), "Asia/Tokyo")
print(slot.tzinfo is timezone.utc) # True
local = slot.astimezone(ZoneInfo("Asia/Tokyo"))
print(9 <= local.hour <= 16) # True
print(local.minute in (0, 30)) # Truerandrange(0, 480, 30) takes a step argument, so the result is always a multiple of 30 and never an awkward minute such as 17. The largest value is 450 minutes, which is 16:30.
Adding a timedelta to an aware datetime moves the wall-clock time. This is fine here because Tokyo has no daylight saving time. In a zone that changes clocks, a slot near a transition can land on a time that doesn't exist or exists twice. For those zones, check the result or keep the arithmetic in UTC.
Edge cases at the seams
| Mistake | What happens | Fix |
|---|---|---|
| `rng.randrange((end - start).days)` | Never returns the end date. | Add 1 to the span. |
| `randrange(0)` for `start == end` without the `+ 1` | `ValueError`: empty range. | Use `span = days + 1`. |
| `rng.sample(range(10), k=20)` | `ValueError`: sample larger than population. | Check `k <= len(population)`. |
| Comparing a mean with `==` | Fails on tiny rounding differences. | Use `math.isclose`, with `abs_tol` when the expected value is 0. |
| `aware - naive` | `TypeError`. | Make both aware, or both naive. |
| `date + timedelta(hours=36)` | Adds 1 day. A `date` uses only the `days` part. | Use a `datetime` if hours matter. |
| `delta.seconds` for total elapsed time | Returns only the seconds part (0 to 86399). | Use `delta.total_seconds()`. |
| Using `random` for a reset token | The values are predictable. | Use `secrets.token_hex` or `secrets.token_urlsafe`. |
Two of these deserve extra care. First, math.isclose compares with a relative tolerance by default, so comparing a value to exactly 0 fails unless you pass abs_tol. For example, math.isclose(1e-12, 0) is False, while math.isclose(1e-12, 0, abs_tol=1e-9) is True. Second, test data built from random is fine, but a token that protects an account is not test data. Generate it with secrets, and don't seed it.
A checklist for combined programs
- Take a
random.Randomas a parameter and don't call the global functions inside library code. - Convert dates to integer offsets before drawing, and convert back with
timedelta. - Define ranges as inclusive or exclusive in a docstring, then compute the span to match.
- Keep stored and computed datetimes aware and in UTC. Convert with
astimezoneonly for display. - Summarize float data with
math.fsum, and compare the results withmath.isclose. - In tests, assert invariants such as counts, ranges, and membership. Use a fixed seed only when you need an exact sequence.
Exercise
Write random_dates(rng, start, end, k) that returns k distinct random dates between start and end inclusive, sorted from earliest to latest. It should raise ValueError when k is larger than the number of dates in the window. Then explain why rng.sample(range(span), k) is better than calling random_date in a loop until you have k unique values.
Show answer
```python is not allowed inside an answer fence here, so the code is described in plain text. Compute span = (end - start).days + 1. If k > span, raise ValueError. Then take offsets = rng.sample(range(span), k), build [start + timedelta(days=o) for o in offsets], and return sorted(that list). The sample approach is better because it guarantees distinct values in one call. A retry loop can run for a very long time when k is close to span, and it never terminates if k is larger than span. Sampling from a range also avoids building a list of every date in the window.
Exercise
A test computes the mean of the gaps between five sampled dates and checks mean * 4 == total_days. It passes with one seed and fails with another. What is wrong, and what is the fix?
Show answer
The mean is a float, so multiplying it back by the number of gaps can differ from the integer total by a tiny rounding error. Whether it does depends on the values the seed produced. Replace the equality check with math.isclose(mean * 4, total_days). Summing the gaps with math.fsum also keeps the accumulated error small.