Skip to content

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(
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(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

Prayer-time results are derived from the exact solar instant in the same order:

  1. Per-prayer adjustments and method_adjustments (integer minutes) are applied to the raw solar time before any rounding.
  2. The adjusted instant is rounded half-up to the nearest minute in UTC (rounded_minute: seconds ≥ 30 round up, with hour/day rollover).
  3. Only the final wall-clock reads run astimezone to 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.

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(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
crescent_geometry_at_sunset(
day: date, coordinates: Coordinates,
delta_t_override: float | None = None,
) -> CrescentGeometry

Topocentric 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(year: float, override: float | None = None) -> float

Isolated 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(arcv_geo_deg: float, width_arcmin: float) -> float

Best-time Yallop q from geocentric ARCV (degrees) and topocentric crescent width (arcminutes). Non-real, non-finite, or float-overflowing inputs raise ValidationError.

yallop_zone(q: float) -> str

Yallop visibility zone ("A"–"F") for a q value. Non-real, non-finite, or float-overflowing inputs raise ValidationError.

odeh_v(arcv_topo_deg: float, width_arcmin: float) -> float

Odeh V from airless topocentric ARCV (degrees) and topocentric crescent width (arcminutes). Non-real, non-finite, or float-overflowing inputs raise ValidationError.

odeh_class(v: float, arcl_deg: float) -> str

Odeh 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(alt_deg: float, elong_deg: float) -> bool

Neo-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(alt_deg: float, elong_deg: float, age_hours: float) -> bool

1992 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(
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

NONE, MUSLIM_WORLD_LEAGUE, EGYPTIAN, KARACHI, UMM_AL_QURA, DUBAI, MOON_SIGHTING_COMMITTEE, NORTH_AMERICA, KUWAIT, QATAR, SINGAPORE, UOIF, JAKIM

MIDDLE_OF_THE_NIGHT, SEVENTH_OF_THE_NIGHT, TWILIGHT_ANGLE

SHAFI, HANAFI

NONE, NEAREST_LATITUDE, NEAREST_DAY, MAKKAH

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)

Coordinates(latitude: float, longitude: float)

Validates that latitude is in [-90, 90] and longitude is in [-180, 180].

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.

AlFalakError (base)
├── AstronomicalError
├── ConfigurationError
└── ValidationError
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,
) -> HijriDate

get_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(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(offsets: dict[str, int] | None = None)
OffsetStore.from_dict(data: dict[str, int]) -> OffsetStore
OffsetStore.from_json(path: str | PathLike) -> OffsetStore
OffsetStore.from_file(path: str | PathLike) -> OffsetStore # alias of from_json
store.apply(hijri: HijriDate, calendar: HijriCalendar) -> HijriDate

Per-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).

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.5 and CI runs the pytest step with PYTHONTZPATH="". End users on Windows may need pip install tzdata. For more details, see Timezone Handling.