API Reference
API Reference
Section titled “API Reference”All public names are importable from the package root:
from alfalak import ( PrayerTimes, Qibla, SunnahTimes, CalculationMethod, CalculationParameters, HighLatitudeRule, Madhab, PolarCircleRule, PrayerAdjustments, Coordinates, Prayer, LunarCoordinates, CrescentGeometry, crescent_geometry_at_sunset, delta_t, AlFalakError, AstronomicalError, ConfigurationError, ValidationError, HijriDate, HijriCalendar, TabularCalendar, UmmAlQuraCalendar, MabimsCalendar, OffsetStore, gregorian_to_hijri, get_calendar,)PrayerTimes
Section titled “PrayerTimes”PrayerTimes( coordinates: tuple[float, float] | Coordinates, date: datetime | DateComponents, calculation_method: CalculationMethod | None = None, calculation_parameters: CalculationParameters | None = None, time_zone: ZoneInfo | None = None,)Exactly one of calculation_method or calculation_parameters must be provided.
Attributes:
| Attribute | Type | Description |
|---|---|---|
imsak |
datetime |
Imsak time (Fajr − imsak_offset, default 10 min) |
fajr |
datetime |
Fajr time |
sunrise |
datetime |
Sunrise time |
syuruk |
datetime |
Syuruk time (== sunrise, MY/SG name) |
ishraq |
datetime |
Ishraq time (sunrise + ishraq_offset, default 15 min) |
dhuha |
datetime |
Start of Dhuha window (sunrise + dhuha_offset, default 28 min) |
dhuhr |
datetime |
Dhuhr time |
asr |
datetime |
Asr time |
maghrib |
datetime |
Maghrib time |
isha |
datetime |
Isha time |
coordinates |
Coordinates |
Location coordinates |
calculation_parameters |
CalculationParameters |
Parameters used |
time_zone |
ZoneInfo | None |
Timezone (if set) |
Methods:
| Method | Returns | Description |
|---|---|---|
time_for_prayer(prayer: Prayer) |
datetime |
Get time for a specific prayer |
time_for_prayer_unrounded(prayer: Prayer) |
datetime |
Post-offset, pre-rounding UTC instant for a specific prayer (per-prayer adjustments/method_adjustments included, half-up minute rounding not yet applied); syuruk is the sunrise instant; when asr saturates to dhuhr/maghrib (polar edge or adjustment-driven clamp) the value is that already-rounded target; Prayer.NONE or non-Prayer inputs raise ConfigurationError |
Qibla(coordinates: tuple[float, float] | Coordinates, method: str = "spherical")method is "spherical" (default) or "ellipsoidal" (Karney inverse on
WGS84); anything else raises ConfigurationError.
Attributes:
| Attribute | Type | Description |
|---|---|---|
direction |
float |
Degrees clockwise from north |
distance_to_makkah_km |
float |
Distance to Makkah in km (per method) |
method |
str |
"spherical" (default) or "ellipsoidal" |
Methods:
| Method | Returns | Description |
|---|---|---|
magnetic_direction(declination_deg) |
float |
Compass heading: true direction minus east-positive declination, unwound to [0, 360); accepts any real number (int/float/Fraction/Decimal) |
SunnahTimes
Section titled “SunnahTimes”SunnahTimes(prayer_times: PrayerTimes)The night is Maghrib to next-day Fajr (offsets included). Duration math runs in UTC, rounds to the minute half-up, then converts to the display zone.
Attributes:
| Attribute | Type | Description |
|---|---|---|
first_third_of_the_night |
datetime |
Maghrib + 1/3 of the night |
middle_of_the_night |
datetime |
Midpoint between Maghrib and Fajr |
last_third_of_the_night |
datetime |
Start of last third of the night |
tahajjud_window |
tuple[datetime, datetime] |
(last_third_of_the_night, next-day Fajr) |
Methods:
| Method | Returns | Description |
|---|---|---|
night_fraction(fraction, start=None, end=None) |
datetime |
Maghrib + fraction of the night (0 < fraction < 1, else ValidationError); accepts int/float/Fraction/Decimal (bool rejected); pass aware start/end datetimes for Isha-anchored or sunset-anchored variants, end must be after start |
night_fraction_unrounded(fraction, start=None, end=None) |
datetime |
Same computation and validation as night_fraction minus the minute rounding and display-zone conversion: Maghrib + fraction of the night in UTC, never rounded; invalid fractions raise ValidationError |
Rounding order
Section titled “Rounding order”Prayer-time results are derived from the exact solar instant in the same order:
- Per-prayer
adjustmentsandmethod_adjustments(integer minutes) are applied to the raw solar time before any rounding. - The adjusted instant is rounded half-up to the nearest minute in UTC
(
rounded_minute: seconds ≥ 30 round up, with hour/day rollover). - Only the final wall-clock reads run
astimezoneto the display zone (time_zone, default UTC); rounding is never re-applied afterwards.
time_for_prayer_unrounded returns the step-2 input: the adjusted,
pre-rounding instant in UTC, per-prayer offsets included. It does not
return raw solar geometry — offsets are already inside the value. One
exception: when asr saturates to dhuhr or maghrib (polar edge or
adjustment-driven clamp), the clamp is the final instant by construction, so
the accessor exposes the rounded clamp target rather than a notional
pre-clamp Asr; this keeps rounded_minute round-tripping to
time_for_prayer.
night_fraction_unrounded returns the exact fraction offset computed from
the same anchors as night_fraction, with only the final minute rounding and
display-zone conversion removed. With the default anchors, those anchors are
the minute-rounded Maghrib/Fajr prayer fields, not raw solar instants;
explicit start/end datetimes are used as supplied, so sub-minute anchors
are preserved. The accessor’s contract is the unrounded fraction offset and
the round-trip guarantee, not sub-minute fidelity of the default anchors.
Accuracy and reference tolerances
Section titled “Accuracy and reference tolerances”Golden tests use two narrow tiers: transit / equation-of-time chains are checked at ±10 s, and USNO rise/set values by minute-resolution equality with the published one-day table. Takwim / e-solat rows are checked against the JAKIM 18°/18° computation; the tables round to the minute and carry a small ihtiyat, and the cited 2025 Kuala Lumpur rows span a −1 to +4 minute official-minus-computed residual. The 20° Singapore preset is not used for that comparison. These bars are never widened to make a port or reference fit; see Citations for the sources behind each golden.
LunarCoordinates
Section titled “LunarCoordinates”LunarCoordinates(julian_day_tt: float)Low-precision geocentric Moon position (Meeus 2nd ed. Ch.47, Tables 47.A–47.B).
Non-real, non-finite, or float-overflowing Julian days (e.g. huge ints)
raise ValidationError.
Attributes:
| Attribute | Type | Description |
|---|---|---|
longitude |
float |
Geocentric ecliptic longitude in degrees [0, 360) |
latitude |
float |
Geocentric ecliptic latitude in degrees |
distance_km |
float |
Geocentric distance in km |
right_ascension |
float |
Right ascension in degrees [0, 360) |
declination |
float |
Declination in degrees |
CrescentGeometry
Section titled “CrescentGeometry”crescent_geometry_at_sunset( day: date, coordinates: Coordinates, delta_t_override: float | None = None,) -> CrescentGeometryTopocentric crescent geometry at local sunset for moon-sighting work:
elongation, geocentric/topocentric arcs of vision, azimuth difference,
crescent width, illumination, moonset lag, and moon age.
Raises AstronomicalError when the Sun does not set on that date;
non-date/Coordinates inputs (or a non-finite override) raise
ValidationError. A datetime is accepted and its calendar date is used.
Attributes:
| Attribute | Type | Description |
|---|---|---|
arcl_deg |
float |
Sun–Moon elongation in degrees |
arcv_geo_deg |
float |
Geocentric arc of vision in degrees |
arcv_topo_deg |
float |
Topocentric (parallax-corrected) arc of vision in degrees |
sun_alt_deg |
float |
True Sun altitude at the evaluated TT instant in degrees (near −0.83° at sunset; differs slightly because the ephemeris runs at TT) |
moon_alt_topo_deg |
float |
Topocentric (parallax-corrected) Moon altitude in degrees — pass this (not ARCV) as alt_deg to the MABIMS helpers |
daz_deg |
float |
Sun–Moon azimuth difference in degrees |
width_arcmin |
float |
Crescent width in arcminutes |
illumination |
float |
Illuminated fraction of the lunar disc [0, 1] |
lag_hours |
float |
Hours from sunset to moonset (negative when the Moon sets first; NaN when no moonset occurs on that date; large positives mean a gibbous/full Moon up well past sunset — the crescent signal is a small positive lag) |
moon_age_days |
float |
Days since the previous new moon (youngest hourly ARCL minimum over the prior 30 days) |
moon_age_at_moonset_days |
float |
Moon age at moonset (sunset age advanced by the lag; NaN when no moonset occurs) — feed this to the MABIMS 1992 age branch |
used_delta_t_s |
float |
Delta-T in seconds used for the TT conversion |
sunset_jd_utc |
float |
Julian Date (UTC) of local sunset |
delta_t
Section titled “delta_t”delta_t(year: float, override: float | None = None) -> floatIsolated Delta-T (TT minus UT1, in seconds) for the lunar path only —
never called by the prayer path. Default is the Espenak polynomial for
2005–2050; pass IERS-observed values via override for modern dates.
Years outside 2005–2050 emit a UserWarning and extrapolate (the value is
still returned); the override path never warns. Non-real, non-finite,
or float-overflowing inputs (e.g. huge ints) raise ValidationError (year is validated even when override=
is set).
yallop_q
Section titled “yallop_q”yallop_q(arcv_geo_deg: float, width_arcmin: float) -> floatBest-time Yallop q from geocentric ARCV (degrees) and topocentric
crescent width (arcminutes). Non-real, non-finite, or float-overflowing
inputs raise ValidationError.
yallop_zone
Section titled “yallop_zone”yallop_zone(q: float) -> strYallop visibility zone ("A"–"F") for a q value. Non-real,
non-finite, or float-overflowing inputs raise ValidationError.
odeh_v
Section titled “odeh_v”odeh_v(arcv_topo_deg: float, width_arcmin: float) -> floatOdeh V from airless topocentric ARCV (degrees) and topocentric
crescent width (arcminutes). Non-real, non-finite, or float-overflowing
inputs raise ValidationError.
odeh_class
Section titled “odeh_class”odeh_class(v: float, arcl_deg: float) -> strOdeh visibility class ("A"–"D") for a V value and elongation
ARCL (degrees). Elongation below 6.4 degrees (Danjon floor) is class
"D" regardless of V. Non-real, non-finite, or float-overflowing inputs
raise ValidationError.
is_neo_mabims_2021
Section titled “is_neo_mabims_2021”is_neo_mabims_2021(alt_deg: float, elong_deg: float) -> boolNeo-MABIMS 2021 visibility: True when the topocentric Moon altitude
(moon_alt_topo_deg from crescent_geometry_at_sunset, not ARCV) is at
least 3 degrees and the elongation is at least 6.4 degrees.
Non-real, non-finite, or float-overflowing inputs raise ValidationError.
is_mabims_1992
Section titled “is_mabims_1992”is_mabims_1992(alt_deg: float, elong_deg: float, age_hours: float) -> bool1992 MABIMS visibility: True when (topocentric Moon altitude
>= 2 degrees and elongation >= 3 degrees) or the Moon age is at
least 8 hours. Pass moon_alt_topo_deg (not ARCV) as the altitude.
Non-real, non-finite, or float-overflowing inputs raise ValidationError.
CalculationParameters
Section titled “CalculationParameters”CalculationParameters( method: CalculationMethod | None = None, adjustments: PrayerAdjustments | None = None, method_adjustments: PrayerAdjustments | None = None, isha_interval: int = 0, fajr_angle: float = 0.0, isha_angle: float = 0.0, polar_circle_rule: PolarCircleRule = PolarCircleRule.NEAREST_LATITUDE, imsak_offset: int = 10, ishraq_offset: int = 15, dhuha_offset: int = 28, elevation_m: float = 0.0, is_ramadan: bool = False,)Minute-count offsets/intervals must be non-negative integers (bool
rejected); elevation_m must be a finite non-negative number of metres;
is_ramadan must be a bool (applies to UMM_AL_QURA only, 120 min total
in Ramadan vs 90 otherwise); dhuha_offset must be >= ishraq_offset.
Violations raise ValidationError (is_ramadan type raises
ConfigurationError).
Attributes (settable):
| Attribute | Type | Default | Description |
|---|---|---|---|
madhab |
Madhab |
Madhab.SHAFI |
Asr calculation method |
high_latitude_rule |
HighLatitudeRule |
MIDDLE_OF_THE_NIGHT |
High latitude rule |
polar_circle_rule |
PolarCircleRule |
NEAREST_LATITUDE |
Polar region strategy |
fajr_angle |
float |
From method | Fajr angle in degrees |
isha_angle |
float |
From method | Isha angle in degrees |
isha_interval |
int |
From method | Isha interval in minutes |
imsak_offset |
int |
10 |
Minutes before Fajr for Imsak |
ishraq_offset |
int |
15 |
Minutes after sunrise for Ishraq |
dhuha_offset |
int |
28 |
Minutes after sunrise for start of Dhuha window (>= ishraq_offset) |
elevation_m |
float |
0.0 |
Observer eye height in metres for dip-of-horizon correction |
is_ramadan |
bool |
False |
Umm al-Qura Ramadan mode (120 min Isha total; preset only) |
method |
CalculationMethod |
NONE |
Calculation method |
adjustments |
PrayerAdjustments |
— | Per-prayer minute offsets |
method_adjustments |
PrayerAdjustments |
— | Method-specific offsets |
CalculationMethod
Section titled “CalculationMethod”NONE, MUSLIM_WORLD_LEAGUE, EGYPTIAN, KARACHI, UMM_AL_QURA, DUBAI, MOON_SIGHTING_COMMITTEE, NORTH_AMERICA, KUWAIT, QATAR, SINGAPORE, UOIF, JAKIM
HighLatitudeRule
Section titled “HighLatitudeRule”MIDDLE_OF_THE_NIGHT, SEVENTH_OF_THE_NIGHT, TWILIGHT_ANGLE
Madhab
Section titled “Madhab”SHAFI, HANAFI
PolarCircleRule
Section titled “PolarCircleRule”NONE, NEAREST_LATITUDE, NEAREST_DAY, MAKKAH
Prayer
Section titled “Prayer”NONE, IMSAK, FAJR, SUNRISE, SYURUK, ISHRAQ, DHUHA, DHUHR, ASR, MAGHRIB, ISHA (listed in chronological definition order, which is canonical — numeric values are frozen for backward compatibility, so do not sort by .value)
Data types
Section titled “Data types”Coordinates
Section titled “Coordinates”Coordinates(latitude: float, longitude: float)Validates that latitude is in [-90, 90] and longitude is in [-180, 180].
PrayerAdjustments
Section titled “PrayerAdjustments”PrayerAdjustments( fajr: int = 0, sunrise: int = 0, dhuhr: int = 0, asr: int = 0, maghrib: int = 0, isha: int = 0, imsak: int = 0, ishraq: int = 0, dhuha: int = 0,)No separate syuruk slot by design: Syuruk aliases sunrise, so sunrise
adjustments flow through to it.
Exceptions
Section titled “Exceptions”AlFalakError (base)├── AstronomicalError├── ConfigurationError└── ValidationErrorHijri calendars
Section titled “Hijri calendars”get_calendar(name: str, *, country: str | None = None, adjustment_days: int = 0)gregorian_to_hijri( dt: datetime, *, calendar: HijriCalendar, coordinates: Coordinates | None = None, params: CalculationParameters | None = None, change_at_sunset: bool = False, offsets: OffsetStore | None = None,) -> HijriDateget_calendar resolves "tabular", "uqu", or "mabims" to a
HijriCalendar. country (one of MY, ID, BN, SG) is required for
— and only for — MabimsCalendar; adjustment_days (in [-2, 2]) is
accepted only by TabularCalendar. Misuse raises ConfigurationError;
out-of-range adjustment_days raises ValidationError.
gregorian_to_hijri converts a Gregorian datetime to a HijriDate on the
given calendar. With change_at_sunset=True the Hijri day rolls over at
that day’s Maghrib (needs coordinates, else ConfigurationError;
Maghrib uses params or default CalculationParameters, and a polar
AstronomicalError propagates unwrapped). Naive datetimes are treated
as UTC. offsets (any object with apply(hijri, calendar), else
ConfigurationError) is applied last; None (default) skips it.
Every calendar implements the same three conversion methods over civil dates
(plus a name property holding the registry key)
(datetime inputs raise ValidationError — pass d.date() or use the
bridge):
| Method | Returns | Description |
|---|---|---|
from_gregorian(d: date) |
HijriDate |
Gregorian civil date → Hijri date; pre-floor inputs raise ValidationError |
to_gregorian(h: HijriDate) |
date |
Hijri date → Gregorian civil date; days past the rule’s month length raise ValidationError |
month_length(year, month) |
int |
29 or 30; non-int years/months (incl. bool) and out-of-range months raise ValidationError |
Calendar notes: the UmmAlQuraCalendar date converter (1423H rule at
Makkah) is not the UMM_AL_QURA prayer preset. MabimsCalendar
exposes its normalized country. TabularCalendar is arithmetic and
routinely differs from observed months by ±1-2 days. OffsetStore
applies per-month (YYYY-MM) day shifts loaded from JSON.
Supported ranges and walk anchors: the observational calendars resolve
month starts by walking forward from a verified anchor, and inputs
before the support floor raise ValidationError instead of returning a
wrong date. UmmAlQuraCalendar supports Gregorian 2002-03-15 onward (1
Muharram 1423H, when the current rule took effect); modern targets walk
from the 1 Muharram 1445H anchor (2023-07-19). MabimsCalendar
(Neo-MABIMS 2021, per-country MY/ID/BN/SG proxies) supports 1
Muharram 1445H onward and walks from the same 2023-07-19 anchor.
TabularCalendar is arithmetic and unbounded below by 1 Muharram 1 AH
(622-07-19 proleptic).
HijriDate
Section titled “HijriDate”HijriDate(year: int, month: int, day: int)Frozen, ordered value type without any calendar rule attached
(bool and non-int fields raise ValidationError; year must be
≥ 1, month in [1, 12], day in [1, 30] — the exact 29/30-day month
length is enforced per calendar at conversion time).
| Attribute/Method | Returns | Description |
|---|---|---|
year / month / day |
int |
Hijri year / month (1–12) / day (1–30) |
isoformat() |
str |
Zero-padded "YYYY-MM-DD" |
OffsetStore
Section titled “OffsetStore”OffsetStore(offsets: dict[str, int] | None = None)OffsetStore.from_dict(data: dict[str, int]) -> OffsetStoreOffsetStore.from_json(path: str | PathLike) -> OffsetStoreOffsetStore.from_file(path: str | PathLike) -> OffsetStore # alias of from_jsonstore.apply(hijri: HijriDate, calendar: HijriCalendar) -> HijriDatePer-month Hijri-day shifts keyed by "YYYY-MM" of the computed
month, values in {-2, -1, 1, 2} (zero and non-int values, bad keys,
and non-dict payloads raise ConfigurationError; unreadable or
unparseable files name the path). apply shifts by Hijri-day
arithmetic on the same calendar’s month lengths, once, with no
re-lookup of the destination month; months without an entry pass
through untouched. to_gregorian ignores the store (display
correction for the Gregorian→Hijri direction only).
Timezone support
Section titled “Timezone support”All prayer times are returned as timezone-aware datetime objects. By default,
the display zone is UTC. Pass time_zone=ZoneInfo("...") to the
PrayerTimes constructor to convert outputs to a specific local zone; the
returned datetimes can also be converted with .astimezone(...). For details
on pinned tzdata, CI configuration, and tested zones, see
Timezone Handling.
- Internal calculations are performed in UTC; rounding is applied in UTC before converting to the display zone (see Rounding order).
- DST transitions (including spring-forward gaps) are handled via
zoneinfo; no wall-clock time is constructed inside a gap. See Timezone Handling for details. - For deterministic behavior across environments (especially CI and Windows),
the dev requirements pin
tzdata==2026.5and CI runs the pytest step withPYTHONTZPATH="". End users on Windows may needpip install tzdata. For more details, see Timezone Handling.
See also
Section titled “See also”- Timezone Handling — zones, DST, and database pinning
- CLI Usage — command-line access to this API (
prayer,qibla,sunnah,hijri,moon-sighting,astro) - Getting Started — quick start guide
- Calculation Methods — method details
- Hijri Converter — calendar rules and conversion walkthrough
- Moon Sighting — crescent geometry and visibility criteria
- Errors — error handling