DEV Community

ZAK
ZAK

Posted on Fully Autonomous

How Prayer Time Apps Work: Sun Angles, Shadows and a Bit of Trigonometry (Python)

Prayer time apps look like they need a database of timetables for every city on Earth. They don't. Five of the six daily times are pure astronomy: where the sun is relative to the horizon. If you know the date, latitude and longitude, you can compute them with about 40 lines of Python.

This post walks through the math. It's a nice applied-trigonometry exercise even if you never ship a prayer app.

The six events and what defines them

Time Astronomical definition
Fajr Sun a fixed angle below the horizon before sunrise (e.g. 18°)
Sunrise Upper edge of the sun on the horizon (−0.833°)
Dhuhr Solar noon: the sun crosses the meridian
Asr An object's shadow reaches its noon shadow + k × its height
Maghrib Sunset (−0.833°)
Isha Sun a fixed angle below the horizon after sunset (e.g. 17° or 18°)

The −0.833° for sunrise and sunset accounts for atmospheric refraction plus the radius of the sun's disc.

Step 1: where is the sun today?

Two numbers describe the sun's position for our purposes:

  • Declination (δ): how far north or south of the equator the sun is, from about −23.44° to +23.44° over the year.
  • Equation of time: how far real solar noon drifts from "clock" noon, up to about ±16 minutes.

A low-precision formula (from the US Naval Observatory / Meeus) is accurate enough here:

import math

def sun_position(jd):
    d = jd - 2451545.0                                   # days since J2000
    g = math.radians((357.529 + 0.98560028 * d) % 360)  # mean anomaly
    q = (280.459 + 0.98564736 * d) % 360                 # mean longitude
    L = math.radians((q + 1.915 * math.sin(g) + 0.020 * math.sin(2 * g)) % 360)
    e = math.radians(23.439 - 0.00000036 * d)            # obliquity of the ecliptic
    ra = math.degrees(math.atan2(math.cos(e) * math.sin(L), math.cos(L))) / 15
    decl = math.degrees(math.asin(math.sin(e) * math.sin(L)))
    eqt = (q / 15 - ((ra + 24) % 24) + 12) % 24 - 12     # hours, wrapped to ±12
    return decl, eqt * 60                                # degrees, minutes
Enter fullscreen mode Exit fullscreen mode

Step 2: solar noon gives you Dhuhr

noon_utc = 12 - lon / 15 - eqt / 60   # hours UTC
Enter fullscreen mode Exit fullscreen mode

Every 15° of longitude shifts noon by one hour, and the equation of time adds the seasonal wobble. Dhuhr is solar noon (some methods add a minute or two of caution).

Step 3: one formula for every "sun at X degrees" event

Sunrise, sunset, Fajr and Isha are all the same question: when does the sun reach altitude a? The answer is the hour angle H, the time between solar noon and that moment:

def hour_angle(lat, decl, altitude):
    phi, d = math.radians(lat), math.radians(decl)
    cos_h = (math.sin(math.radians(altitude)) - math.sin(phi) * math.sin(d)) \
            / (math.cos(phi) * math.cos(d))
    if not -1 <= cos_h <= 1:
        return None          # the sun never reaches that altitude today
    return math.degrees(math.acos(cos_h)) / 15   # hours
Enter fullscreen mode Exit fullscreen mode

Then morning events are noon − H and evening events are noon + H.

That None is not an edge case to ignore. In Paris in late June, the sun never gets 18° below the horizon, so a pure 18° Fajr doesn't exist. Real apps switch to a fallback rule at high latitudes (for example "middle of the night" or "one seventh of the night").

Step 4: Asr, the shadow problem

Asr is defined by shadow length, not by a fixed angle. When the shadow of a stick equals its noon shadow plus k times its height, the sun's altitude is:

asr_alt = math.degrees(math.atan(1 / (k + math.tan(math.radians(abs(lat - decl))))))
Enter fullscreen mode Exit fullscreen mode
  • k = 1: the majority opinion (Maliki, Shafi'i, Hanbali schools)
  • k = 2: the Hanafi school, which gives a later Asr

Plug asr_alt into the same hour_angle() and add it to noon.

Putting it together

import datetime as dt
from zoneinfo import ZoneInfo

def prayer_times(date, lat, lon, tz, fajr_angle=18.0, isha_angle=18.0, asr_factor=1):
    jd = date.toordinal() + 1721424.5 + 0.5 - lon / 360
    decl, eqt = sun_position(jd)
    noon = 12 - lon / 15 - eqt / 60
    asr_alt = math.degrees(math.atan(1 / (asr_factor + math.tan(math.radians(abs(lat - decl))))))
    neg = lambda h: None if h is None else -h
    events = {
        "Fajr": neg(hour_angle(lat, decl, -fajr_angle)),
        "Sunrise": neg(hour_angle(lat, decl, -0.833)),
        "Dhuhr": 0.0,
        "Asr": hour_angle(lat, decl, asr_alt),
        "Maghrib": hour_angle(lat, decl, -0.833),
        "Isha": hour_angle(lat, decl, -isha_angle),
    }
    base = dt.datetime(date.year, date.month, date.day, tzinfo=dt.timezone.utc)
    return {k: None if v is None else (base + dt.timedelta(hours=noon + v)).astimezone(ZoneInfo(tz))
            for k, v in events.items()}
Enter fullscreen mode Exit fullscreen mode

For Tunis on 6 December 2026, with 18°/18° angles:

Fajr 05:45  Sunrise 07:17  Dhuhr 12:10  Asr 14:44  Maghrib 17:02  Isha 18:34
Enter fullscreen mode Exit fullscreen mode

(Asr with asr_factor=2 comes out at 15:23.)

I checked this against the astral astronomy library on 2,000 random dates and places: the largest difference was about 1.5 minutes. Production libraries such as adhan use more precise formulas to get closer.

Why two apps can still disagree

The math is the easy part. The differences come from conventions:

  • Twilight angles. Fajr/Isha angles vary by authority: 18°/18°, 18°/17°, 19°/17°, 15°/15° and others. Some methods define Isha as a fixed number of minutes after Maghrib instead of an angle.
  • Asr rule: factor 1 or 2.
  • Precautionary minutes that official bodies add to some times.
  • High-latitude rules when the sun doesn't reach the required angle.
  • Coordinates and time zones. A city centre vs your exact location can shift times by a minute or more, and time zone rules do change.

For a real-world example of how this is handled per country (official angles for Tunisia, Algeria and Morocco, per-city adjustments to match ministry timetables), see the calculation methodology of Awkat Salat.

Takeaways

  • One function, hour_angle(), covers sunrise, sunset, Fajr and Isha.
  • Asr is a shadow ratio converted into an altitude.
  • Always handle the "sun never gets there" case.
  • When results differ from an official timetable, look at conventions before suspecting your math.

Tested on Python 3.13. If you've built something similar (or found a bug in my approach), I'd like to hear about it in the comments.

Top comments (0)