Below is a compact, self-contained helper that
- “hashes” an input date (i.e. turns it into a deterministic integer via SHA-256)
- maps that integer onto a target interval
[begin_date, end_date] (inclusive)
- spits out a new, still-valid
datetime.date.
You always get the same output for the same (input_date, begin, end, salt) tuple, yet the results look random and are nicely spread across the interval.
from __future__ import annotations # for Python 3.9 ‑ 3.10 (optional)
import hashlib
import datetime as _dt
from typing import Union
DateLike = Union[str, _dt.date, _dt.datetime]
def hashed_date(
src_date: DateLike,
begin: DateLike,
end: DateLike,
*,
salt: str = ""
) -> _dt.date:
"""
Deterministically map `src_date` to a (pseudo-)random date in [`begin`, `end`].
Parameters
----------
src_date : date | datetime | str
The original date to hash. If str, any ISO-like format supported by
`datetime.fromisoformat()` works (e.g. '2024-03-15').
begin, end : date | datetime | str
Boundaries of the target interval (inclusive). Order does not matter.
salt : str, optional
Extra string blended into the hash so you can get different mappings
without changing the algorithm. Default: "" (empty).
Returns
-------
datetime.date
A date inside the requested range.
Raises
------
ValueError
If begin == end == None or the range length is < 0.
"""
# --- 1. coerce everything to `datetime.date` --------------------------------
def _to_date(d: DateLike) -> _dt.date:
if isinstance(d, _dt.datetime):
return d.date()
if isinstance(d, _dt.date):
return d
# assume str
return _dt.date.fromisoformat(d)
src_date = _to_date(src_date)
begin, end = map(_to_date, (begin, end))
# allow caller to swap begin/end
if begin > end:
begin, end = end, begin
span_days = (end - begin).days
if span_days < 0:
raise ValueError("`begin` and `end` cannot be the same.") # unreachable really
# --- 2. build the hash -------------------------------------------------------
# We feed: src_date + salt + length of span (guards against subtle collisions)
blob = f"{src_date.isoformat()}|{salt}|{span_days}".encode()
digest = hashlib.sha256(blob).digest()
# turn first 8 bytes into an unsigned 64-bit int for portability
hashed_int = int.from_bytes(digest[:8], "big", signed=False)
# --- 3. map onto [0, span_days] --------------------------------------------
offset = hashed_int % (span_days + 1) # +1 makes the range inclusive
return begin + _dt.timedelta(days=offset)
# -------------------------------------------------------------------------------
# Quick demo / self-test
# -------------------------------------------------------------------------------
if __name__ == "__main__":
src = "2020-02-29" # leap day :-)
start = "2030-01-01"
stop = "2030-12-31"
for s in ("", "pepper", "another-salt"):
print(f"salt = {s!r} => {hashed_date(src, start, stop, salt=s)}")
Example run:
salt = '' => 2030-07-11
salt = 'pepper' => 2030-02-23
salt = 'another-salt' => 2030-11-19
Why it works
• SHA-256 gives an effectively uniform 256-bit “random” integer for each unique input.
• Taking that integer mod the number of days in the interval distributes results evenly (small bias possible only if the span is not a power of two, but SHA-256 output is so uniform that any bias is negligible).
• Adding the offset to begin converts the numeric result back into a valid, calendar-aware date.