Skip to main content

django-bizcal

PyPI version Python versions CI License: MIT

django-bizcal is a Python library for Django projects that need business calendars: official and custom holidays, intraday schedules, calendar composition, and timezone-aware business-time arithmetic.

Typical uses are SLA clocks, due dates, approvals, support desks, tenant-specific calendars, and country-specific business hours.

Features

  • Pure domain core with no ORM coupling.
  • Official holidays via holidays.
  • Custom organization or tenant holidays in memory.
  • Intraday schedules with multiple windows per weekday.
  • Business-time arithmetic in hours, minutes, and whole business days.
  • Work blocks that cross midnight, so an overnight shift is a single block.
  • Calendar composition with union, intersection, difference, and override.
  • Explicit timezone support based on zoneinfo.
  • SLA and due-date helpers built on top of business calendars.
  • Declarative deadline policies for common operational rules and cutoffs.
  • Django app with namespaced settings and service helpers.
  • Optional database-backed holiday closures and per-day schedule overrides for named Django calendars.
  • Context-aware Django calendar resolution for tenant, client, or region specific lookups.
  • Context-aware Django deadline-policy resolution for tenant, priority, or workflow specific SLA rules.

Installation

pip install django-bizcal

For local development:

pip install -e ".[dev]"

Quickstart

from datetime import datetime
from zoneinfo import ZoneInfo

from django_bizcal import UnionCalendar, WorkingCalendar

cl = WorkingCalendar.from_country(
    country="CL",
    years=[2026, 2027],
    tz="America/Santiago",
    weekly_schedule={
        0: [("09:00", "13:00"), ("14:00", "18:00")],
        1: [("09:00", "13:00"), ("14:00", "18:00")],
        2: [("09:00", "13:00"), ("14:00", "18:00")],
        3: [("09:00", "13:00"), ("14:00", "18:00")],
        4: [("09:00", "13:00"), ("14:00", "17:00")],
    },
    extra_holidays=["2026-12-24", "2026-12-31"],
)

mx = WorkingCalendar.from_country(
    country="MX",
    years=[2026, 2027],
    tz="America/Mexico_City",
    weekly_schedule={
        0: [("09:00", "18:00")],
        1: [("09:00", "18:00")],
        2: [("09:00", "18:00")],
        3: [("09:00", "18:00")],
        4: [("09:00", "18:00")],
    },
)

regional = UnionCalendar([cl, mx], tz="UTC")

start = datetime(2026, 1, 5, 15, 0, tzinfo=ZoneInfo("UTC"))
deadline = regional.add_business_hours(start, 10)
elapsed = regional.business_minutes_between(start, deadline)

Business days

add_business_days(...) moves a datetime by whole business days and keeps its wall-clock time, skipping weekends and holidays:

santiago = ZoneInfo("America/Santiago")
wednesday = datetime(2026, 10, 7, 16, 30, tzinfo=santiago)

assert cl.add_business_days(wednesday, 1) == datetime(2026, 10, 8, 16, 30, tzinfo=santiago)
# Saturday, Sunday and the October 12 holiday are skipped.
assert cl.add_business_days(wednesday, 3) == datetime(2026, 10, 13, 16, 30, tzinfo=santiago)
assert cl.add_business_days(wednesday, -1) == datetime(2026, 10, 6, 16, 30, tzinfo=santiago)

Rules:

  • A start outside business time is first moved to the next business datetime, or to the previous one when days is negative. Wednesday 20:00 plus one business day is Friday 09:00.
  • If the target day does not cover the wall-clock time, the result moves into that day: to the next opening, or back to the closing when the time is past it. Thursday 17:30 plus one business day is Friday 17:00 when Friday closes at 17:00.
  • The result is returned in the timezone of the start.

The calendar always has a timezone. The datetime passed as the start must also carry one: a naive datetime raises ValidationError, because the library cannot tell which local time it refers to. With Django's USE_TZ = True, timezone.now() and model DateTimeField values are already aware. Otherwise, attach the calendar timezone first:

from django.utils import timezone

start = timezone.make_aware(naive_start, calendar.tz)
calendar.add_business_days(start, 1)

To land on a fixed boundary instead of the start's wall-clock time, use business_deadline_at_close(...) or BusinessDaysPolicy(..., at="opening"). examples/business_days.py combines hours, days, and both.

Overnight work blocks

A block that starts one day and ends the next is a single schedule entry, written as (start, end, end_offset_days):

from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

from django_bizcal import WorkingCalendar

mine = WorkingCalendar(
    tz="America/Santiago",
    weekly_schedule={weekday: [("22:00", "06:00", 1)] for weekday in range(5)},
)

santiago = ZoneInfo("America/Santiago")
shift_start = datetime(2026, 3, 2, 22, 0, tzinfo=santiago)
shift_end = datetime(2026, 3, 3, 6, 0, tzinfo=santiago)

assert mine.business_time_between(shift_start, shift_end) == timedelta(hours=8)
assert mine.add_business_hours(shift_start, 5) == datetime(2026, 3, 3, 3, 0, tzinfo=santiago)
assert mine.is_business_day("2026-03-03") is True

Day queries report coverage clipped to the civil day, so the two halves of the night tile the timeline exactly:

# Monday: [22:00 -> Tuesday 00:00)
mine.business_windows_for_day("2026-03-02")
# Tuesday: [00:00 -> 06:00), then Tuesday's own shift [22:00 -> Wednesday 00:00)
mine.business_windows_for_day("2026-03-03")
# Monday, unclipped: [22:00 -> Tuesday 06:00), the whole block
mine.business_blocks_for_day("2026-03-02")

By default a holiday suppresses only the blocks that start on it, so a shift already running into a holiday morning is preserved. Pass holiday_truncates_overnight=True to truncate the incoming block at midnight instead.

Deadline helpers

from datetime import timedelta

from django_bizcal import breach_at, deadline_for, due_on_next_business_day

target = deadline_for(start, timedelta(hours=8), calendar=regional)
breach_time = breach_at(start, timedelta(hours=8), calendar=regional)
next_cutoff = due_on_next_business_day("2026-03-06", calendar=regional, at="closing")

assert target.deadline == breach_time
assert target.is_breached(at=breach_time) is False

The same helpers are also available as calendar instance methods:

target = regional.deadline_for(start, timedelta(hours=8))
breach_time = regional.breach_at(start, timedelta(hours=8))
next_cutoff = regional.due_on_next_business_day("2026-03-06", at="closing")

Declarative deadline policies

from datetime import datetime
from zoneinfo import ZoneInfo

from django_bizcal import DeadlinePolicyBuilder

policy = DeadlinePolicyBuilder.from_dict(
    {
        "type": "cutoff",
        "cutoff": "15:00",
        "before": {"type": "close_of_business"},
        "after": {"type": "next_business_day", "at": "closing"},
    }
)

deadline = policy.resolve(
    datetime(2026, 3, 5, 16, 0, tzinfo=ZoneInfo("America/Santiago")),
    calendar=cl,
)

config = DeadlinePolicyBuilder.to_dict(policy)

Built-in policy types:

  • business_duration
  • close_of_business
  • business_days
  • same_business_day
  • next_business_day
  • business_days_at_close
  • cutoff

Policies can also be resolved directly from a calendar instance:

deadline = cl.resolve_deadline_policy(
    datetime(2026, 3, 5, 16, 0, tzinfo=ZoneInfo("America/Santiago")),
    policy,
)

deadline = cl.resolve_deadline_policy_dict(
    datetime(2026, 3, 5, 16, 0, tzinfo=ZoneInfo("America/Santiago")),
    {
        "type": "business_duration",
        "business_hours": 8,
    },
)

Django integration

Add the app to INSTALLED_APPS:

INSTALLED_APPS = [
    ...,
    "django_bizcal",
]

Configure a default calendar:

BIZCAL_DEFAULT_TIMEZONE = "America/Santiago"
BIZCAL_DEFAULT_COUNTRY = "CL"
BIZCAL_PRELOAD_YEARS = [2026, 2027]
BIZCAL_DEFAULT_CALENDAR = {
    "type": "working",
    "tz": "America/Santiago",
    "country": "CL",
    "years": [2026, 2027],
    "weekly_schedule": {
        "0": [["09:00", "13:00"], ["14:00", "18:00"]],
        "1": [["09:00", "13:00"], ["14:00", "18:00"]],
        "2": [["09:00", "13:00"], ["14:00", "18:00"]],
        "3": [["09:00", "13:00"], ["14:00", "18:00"]],
        "4": [["09:00", "13:00"], ["14:00", "17:00"]],
    },
    "extra_holidays": ["2026-12-24", "2026-12-31"],
}

Consume it from application code:

from django_bizcal.django_api import get_default_calendar

calendar = get_default_calendar()
deadline = calendar.add_business_hours(ticket.created_at, 8)

For projects with more than one operational calendar, define a named registry:

BIZCAL_DEFAULT_TIMEZONE = "UTC"
BIZCAL_DEFAULT_CALENDAR_NAME = "support"
BIZCAL_CALENDARS = {
    "support": {
        "type": "working",
        "tz": "UTC",
        "weekly_schedule": {
            "0": [["09:00", "18:00"]],
            "1": [["09:00", "18:00"]],
            "2": [["09:00", "18:00"]],
            "3": [["09:00", "18:00"]],
            "4": [["09:00", "18:00"]],
        },
    },
    "operations_latam": {
        "type": "union",
        "tz": "UTC",
        "children": [
            {
                "type": "working",
                "country": "CL",
                "years": [2026, 2027],
                "tz": "America/Santiago",
                "weekly_schedule": {
                    "0": [["09:00", "18:00"]],
                    "1": [["09:00", "18:00"]],
                    "2": [["09:00", "18:00"]],
                    "3": [["09:00", "18:00"]],
                    "4": [["09:00", "18:00"]],
                },
            },
            {
                "type": "working",
                "country": "MX",
                "years": [2026, 2027],
                "tz": "America/Mexico_City",
                "weekly_schedule": {
                    "0": [["09:00", "18:00"]],
                    "1": [["09:00", "18:00"]],
                    "2": [["09:00", "18:00"]],
                    "3": [["09:00", "18:00"]],
                    "4": [["09:00", "18:00"]],
                },
            },
        ],
    },
}

Use named calendars from application code:

from django_bizcal.django_api import get_calendar, get_default_calendar

support = get_default_calendar()
regional_ops = get_calendar("operations_latam")

For tenant-, client-, or region-aware lookups, configure a contextual resolver:

from django_bizcal.django_api import CalendarResolution


def support_calendar_resolver(*, context, bizcal_settings):
    region = str(context["region"]).strip().lower()
    if region in {"cl", "mx"}:
        return f"support_{region}"
    tenant = str(context["tenant"]).strip().lower()
    return CalendarResolution.for_config(
        {
            "type": "working",
            "tz": "America/Santiago",
            "weekly_schedule": {
                "0": [["09:00", "18:00"]],
                "1": [["09:00", "18:00"]],
                "2": [["09:00", "18:00"]],
                "3": [["09:00", "18:00"]],
                "4": [["09:00", "18:00"]],
            },
        },
        name=f"tenant:{tenant}",
        cache_key=f"tenant:{tenant}",
    )


BIZCAL_CALENDAR_RESOLVER = support_calendar_resolver

Then resolve calendars from application context:

from django_bizcal.django_api import get_calendar_for

regional_support = get_calendar_for(region="cl")
tenant_calendar = get_calendar_for(tenant="acme", region="cl")

You can also configure named deadline policies in Django settings:

BIZCAL_DEADLINE_POLICIES = {
    "support_p1": {
        "type": "business_duration",
        "business_hours": 4,
    },
    "vendor_follow_up": {
        "type": "business_days",
        "business_days": 2,
        "at": "13:30",
        "include_start": True,
    },
    "support_cutoff": {
        "type": "cutoff",
        "cutoff": "15:00",
        "before": {"type": "close_of_business"},
        "after": {"type": "next_business_day", "at": "closing"},
    },
}

And, when policy selection depends on business context, resolve it the same way you already resolve calendars:

from django_bizcal.django_api import DeadlinePolicyResolution


def support_policy_resolver(*, context, bizcal_settings):
    priority = str(context["priority"]).strip().lower()
    if priority == "critical":
        return "support_p1"
    tenant = str(context["tenant"]).strip().lower()
    return DeadlinePolicyResolution.for_config(
        {"type": "same_business_day", "at": "closing"},
        name=f"tenant_policy:{tenant}:{priority}",
        cache_key=f"tenant_policy:{tenant}:{priority}",
    )


BIZCAL_DEADLINE_POLICY_RESOLVER = support_policy_resolver

And use the same deadline helpers on top of contextual calendars:

from datetime import timedelta

from django_bizcal.django_api import deadline_for, get_calendar_for, now

calendar = get_calendar_for(tenant="acme", region="cl")
deadline = deadline_for(now(), timedelta(hours=8), calendar=calendar)

Or with the calendar method:

calendar = get_calendar_for(tenant="acme", region="cl")
deadline = calendar.deadline_for(now(), timedelta(hours=8))

Or compute deadlines from a named policy:

from django_bizcal.django_api import (
    compute_deadline,
    get_deadline_policy,
    get_deadline_policy_config,
    get_deadline_policy_for,
)

deadline = compute_deadline(
    "support_cutoff",
    now(),
    tenant="acme",
    region="cl",
)

policy = get_deadline_policy("support_cutoff")
policy_config = get_deadline_policy_config("support_cutoff")
contextual_policy = get_deadline_policy_for(
    tenant="acme",
    region="cl",
    priority="critical",
)
contextual_deadline = compute_deadline(
    policy_name=None,
    start=now(),
    tenant="acme",
    region="cl",
    priority="critical",
)

Calendars resolved through get_default_calendar(), get_calendar(name), and get_calendar_for(...) also carry their logical calendar_name, so BusinessDeadline.calendar_name is filled automatically in the common Django flows.

More examples:

  • examples/business_days.py
  • examples/sla_deadlines.py
  • examples/helpdesk_sla.py
  • examples/deadline_policies.py

Resolver return values can be:

  • a logical calendar name such as "support_cl"
  • a serializable calendar config mapping
  • CalendarResolution, which can carry both a config and a logical name plus an optional cache_key

When BIZCAL_ENABLE_DB_MODELS = True, a contextual resolution with CalendarResolution(name=..., config=...) also participates in persisted holiday and per-day override application for that logical name.

Persisted holiday closures and per-day overrides can be enabled for named Django calendars:

BIZCAL_ENABLE_DB_MODELS = True

from datetime import date

from django_bizcal.django_api import (
    CalendarHoliday,
    set_calendar_day_override,
    set_calendar_holiday,
)

CalendarHoliday.objects.create(
    calendar_name="support",
    day=date(2026, 12, 24),
    name="Company shutdown",
)

set_calendar_holiday("support", date(2026, 12, 31), name="Year end close")
set_calendar_day_override(
    "support",
    date(2026, 12, 24),
    [("09:00", "13:00")],
    name="Christmas Eve half day",
)

Once enabled, get_default_calendar() and get_calendar(name) automatically apply persisted rows that match the logical calendar name:

  • CalendarHoliday closes a full day
  • CalendarDayOverride replaces the day with one or more explicit intraday windows

If both exist for the same day, the per-day override wins because it is more specific. The affected cached named calendar is invalidated automatically after persisted changes, whether they happen through the Django service helpers, the Django admin, or direct ORM saves and deletes after transaction commit. When the optional models are enabled, the Django admin also includes bulk activate/deactivate actions plus window summaries for one-off intraday schedules.

Preferred Django-specific imports:

from django_bizcal.django_api import get_calendar, set_calendar_holiday

If you need to inspect persisted state without working with ORM relations directly, the Django service layer also exposes helpers such as list_calendar_holiday_days(...), list_calendar_day_override_windows(...), and get_calendar_day_override_windows(...).

Calendar builder

from django_bizcal import CalendarBuilder

calendar = CalendarBuilder.from_dict(
    {
        "type": "union",
        "tz": "UTC",
        "children": [
            {
                "type": "working",
                "country": "CL",
                "years": [2026, 2027],
                "tz": "America/Santiago",
                "weekly_schedule": {
                    "0": [["09:00", "18:00"]],
                    "1": [["09:00", "18:00"]],
                    "2": [["09:00", "18:00"]],
                    "3": [["09:00", "18:00"]],
                    "4": [["09:00", "18:00"]],
                },
            },
            {
                "type": "working",
                "country": "MX",
                "years": [2026, 2027],
                "tz": "America/Mexico_City",
                "weekly_schedule": {
                    "0": [["09:00", "18:00"]],
                    "1": [["09:00", "18:00"]],
                    "2": [["09:00", "18:00"]],
                    "3": [["09:00", "18:00"]],
                    "4": [["09:00", "18:00"]],
                },
            },
        ],
    }
)

The builder also supports serialization back to declarative config:

from django_bizcal import CalendarBuilder

config = CalendarBuilder.to_dict(calendar)
restored = CalendarBuilder.from_dict(config)

Day and boundary helpers

The public API also includes day- and boundary-level helpers:

  • add_business_hours(...), add_business_minutes(...), add_business_days(...)
  • iter_business_days(...), list_business_days(...), count_business_days(...)
  • next_business_day(...), previous_business_day(...)
  • opening_for_day(...), closing_for_day(...)
  • next_opening_datetime(...), previous_closing_datetime(...)

Typed declarative config helpers are also exported for IDE and static typing support:

  • CalendarConfig
  • WorkingCalendarConfig
  • UnionCalendarConfig
  • IntersectionCalendarConfig
  • DifferenceCalendarConfig
  • OverrideCalendarConfig

Architecture

  • The domain core lives in src/django_bizcal and stays framework-light.
  • WorkingCalendar handles business schedules and holiday lookup.
  • Composition calendars project child windows into a reference timezone.
  • The Django layer wraps settings, AppConfig, service helpers, and optional persistence for named calendar closures and per-day overrides.

See the full documentation in:

Compatibility

  • Python 3.11+
  • Officially tested against Django 5.2 LTS and 6.0
  • CI covers the supported upstream Python and Django combinations documented in docs/stability.md

Limitations

  • Official holiday lookup requires the relevant years to be preloaded.
  • Wall-clock times are interpreted with zoneinfo; DST transitions affect real elapsed durations.
  • The library persists named calendar closures and per-day overrides, but not full calendar definitions or arbitrary composition graphs.
  • A work block may cross at most one midnight, so a single block cannot exceed 24 hours.
  • business_windows_for_day(...) reports coverage clipped to the civil day. While an overnight block is open across midnight, opening_for_day(...), closing_for_day(...), next_opening_datetime(...), and previous_closing_datetime(...) report midnight rather than the block's own boundaries. Use WorkingCalendar.business_blocks_for_day(...) for the whole unclipped block.
  • WorkingCalendar.business_blocks_for_day(...) is not available on composite calendars, whose children already report coverage clipped to civil days.

Release

python -m build
pytest

Releases are published from GitHub Actions with PyPI Trusted Publishing. See docs/release.md.

Support

Report bugs and request features through GitHub issues.

Metadata

Release files for django-bizcal 0.12.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-bizcal 0.12.1
File Size Uploaded Provenance Actions
django_bizcal-0.12.1.tar.gz 90.3 kB With provenance Details for django_bizcal-0.12.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-bizcal 0.12.1
File Interpreter ABI Platform Actions
django_bizcal-0.12.1-py3-none-any.whl Python 3 none any Details for django_bizcal-0.12.1-py3-none-any.whl

Total release size: 145.1 kB

Release files / django_bizcal-0.12.1.tar.gz

Download URL django_bizcal-0.12.1.tar.gz
Size 90.3 kB
Tags Source
SHA-256 checksum
How to use checksums
fff3ce2b618d65b1b4f40ea70b4f730703adba639c6fc53578ee213a35be451b
BLAKE2b-256 checksum
How to use checksums
a358e1bc0a380ecbf4992385695230971f2d74a05ad95aafb4d60edcee17775c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 5, 2026.

Transparency log

Release files / django_bizcal-0.12.1-py3-none-any.whl

Download URL django_bizcal-0.12.1-py3-none-any.whl
Size 54.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cf77b9d17c62a6aa2a290323663b8d717abb18e809d0e298cffa12df63b1d8f8
BLAKE2b-256 checksum
How to use checksums
aec05f61c0089af8bc2c6445519d8a2b9fa5d9b933e96aff5a1ee7b3acf9901e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 5, 2026.

Transparency log

Security for django-bizcal 0.12.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for django_bizcal-0.12.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page