Implementation · Python
Persian (Jalali) calendar in Python
Dependency-free Python implementation of the Jalali (Persian, Solar Hijri) calendar: leap years, date validation, Gregorian and Julian Day conversion, weekday and day of year. Verified day by day for 1178–3000 AP. MIT license.
- Requires
- Python 3.8+
- Tested with
- Python 3.13
- Cross-checked against
- ICU4C 76.1–79.1 (
ctypes), every year of the full range - Language-specific checks
TypeErrorfor non-integers,boolrejected (isinstance(True, int))- License
- MIT
- Version
- 1.0.0
Quick start
Copy or download the source file into your project (no dependencies).
Optionally, run its tests. The .zip keeps the folder layout they expect; from the language folder:
implementations/pythonpython -m unittestCall the shared API: function reference
Source
persian_calendar.py
· 210 lines# Copyright (C) 2026 Goudarz Jafari <hi@goudarzjafari.com>
# SPDX-License-Identifier: MIT
"""Solar Hijri (Persian, Jalali, Shamsi) calendar.
Algorithm: the 33-year arithmetic rule plus a table of 78 corrections,
the same algorithm used by ICU 77.1+ and ICU4X.
It matches the astronomical calendar computed on the 52.5 E meridian for
every year from 1178 to 3000 AP (1799-3621 CE), including the official
University of Tehran Calendar Center table (1206-1498 AP).
Outside 1178-3000 AP the functions still work (arithmetic extrapolation),
but the results are not guaranteed to match the astronomical calendar.
Inputs are accepted for years MIN_YEAR..MAX_YEAR; anything else raises
ValueError, and non-integers raise TypeError.
Pure integer arithmetic, no dependencies. Python's // is floor division,
which the formulas require.
"""
# Years checked against the astronomical calendar.
VERIFIED_MIN_YEAR = 1178
VERIFIED_MAX_YEAR = 3000
# Accepted input range. Within it every intermediate value fits in 32 bits.
MIN_YEAR = -100_000
MAX_YEAR = 100_000
MIN_JDN = -34_576_287 # 1 Farvardin -100000 (Gregorian -99379-03-29)
MAX_JDN = 38_472_562 # 29 Esfand 100000 (Gregorian 100622-03-13)
# Julian Day Number of 1 Farvardin 1 as the 33-year formula computes it.
# A calibration constant: the historical (astronomical) Nowruz of year 1 was
# one day later; only years 1178-3000 are verified against astronomy.
_EPOCH_JDN = 1948320
# Years the 33-year rule calls leap but are not; the next year is leap instead.
NON_LEAP_CORRECTION = frozenset((
1502, 1601, 1634, 1667, 1700, 1733, 1766, 1799, 1832, 1865, 1898, 1931,
1964, 1997, 2030, 2059, 2063, 2096, 2129, 2158, 2162, 2191, 2195, 2224,
2228, 2257, 2261, 2290, 2294, 2323, 2327, 2356, 2360, 2389, 2393, 2422,
2426, 2455, 2459, 2488, 2492, 2521, 2525, 2554, 2558, 2587, 2591, 2620,
2624, 2653, 2657, 2686, 2690, 2719, 2723, 2748, 2752, 2756, 2781, 2785,
2789, 2818, 2822, 2847, 2851, 2855, 2880, 2884, 2888, 2913, 2917, 2921,
2946, 2950, 2954, 2979, 2983, 2987,
))
MONTH_NAMES_FA = ("فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور",
"مهر", "آبان", "آذر", "دی", "بهمن", "اسفند")
MONTH_NAMES_EN = ("Farvardin", "Ordibehesht", "Khordad", "Tir", "Mordad", "Shahrivar",
"Mehr", "Aban", "Azar", "Dey", "Bahman", "Esfand")
# Index 0 = Saturday, the first day of the Iranian week.
WEEKDAY_NAMES_FA = ("شنبه", "یکشنبه", "دوشنبه", "سهشنبه", "چهارشنبه", "پنجشنبه", "جمعه")
WEEKDAY_NAMES_EN = ("Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
_GREGORIAN_MIN_YEAR = -99_379
_GREGORIAN_MAX_YEAR = 100_622
def _is_int(value):
return isinstance(value, int) and not isinstance(value, bool)
def _check_int(name, value):
if not _is_int(value):
raise TypeError(f"{name} must be an int, not {type(value).__name__}")
def _check_year(year):
_check_int("year", year)
if not MIN_YEAR <= year <= MAX_YEAR:
raise ValueError(f"year out of range [{MIN_YEAR}, {MAX_YEAR}]: {year}")
def is_leap_year(year):
"""True if the Persian year has 366 days (Esfand has 30 days)."""
_check_year(year)
if year in NON_LEAP_CORRECTION:
return False
if year - 1 in NON_LEAP_CORRECTION:
return True
return (25 * year + 11) % 33 < 8
def days_in_month(year, month):
"""29, 30 or 31."""
_check_year(year)
_check_int("month", month)
if not 1 <= month <= 12:
raise ValueError(f"month out of range [1, 12]: {month}")
if month <= 6:
return 31
if month <= 11:
return 30
return 30 if is_leap_year(year) else 29
def is_valid_date(year, month, day):
"""True for a real Persian date in the accepted range; never raises."""
if not (_is_int(year) and _is_int(month) and _is_int(day)):
return False
if not (MIN_YEAR <= year <= MAX_YEAR and 1 <= month <= 12):
return False
return 1 <= day <= days_in_month(year, month)
def _nowruz_jdn(year):
"""JDN of 1 Farvardin of the given year."""
jdn = _EPOCH_JDN + 365 * (year - 1) + (8 * year + 21) // 33
if year - 1 in NON_LEAP_CORRECTION:
jdn -= 1
return jdn
def _days_before_month(month):
return 31 * (month - 1) if month <= 7 else 30 * (month - 1) + 6
def _check_date(year, month, day):
if not is_valid_date(year, month, day):
for name, value in (("year", year), ("month", month), ("day", day)):
_check_int(name, value)
raise ValueError(f"invalid Persian date: {year}/{month}/{day}")
def to_jdn(year, month, day):
"""Julian Day Number of a Persian date."""
_check_date(year, month, day)
return _nowruz_jdn(year) + _days_before_month(month) + day - 1
def _check_jdn(jdn):
_check_int("jdn", jdn)
if not MIN_JDN <= jdn <= MAX_JDN:
raise ValueError(f"jdn out of range [{MIN_JDN}, {MAX_JDN}]: {jdn}")
def from_jdn(jdn):
"""Persian (year, month, day) of a Julian Day Number."""
_check_jdn(jdn)
year = 1 + (33 * (jdn - _EPOCH_JDN) + 3) // 12053 # estimate, then correct
while jdn >= _nowruz_jdn(year + 1):
year += 1
while jdn < _nowruz_jdn(year):
year -= 1
day_of_year = jdn - _nowruz_jdn(year) # 0-based
if day_of_year < 186:
return year, day_of_year // 31 + 1, day_of_year % 31 + 1
day_of_year -= 186
return year, day_of_year // 30 + 7, day_of_year % 30 + 1
def _gregorian_days_in_month(year, month):
if month == 2:
return 29 if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) else 28
return 30 if month in (4, 6, 9, 11) else 31
def gregorian_to_jdn(year, month, day):
"""JDN of a proleptic Gregorian date. Raises ValueError for an invalid date."""
for name, value in (("year", year), ("month", month), ("day", day)):
_check_int(name, value)
if not (_GREGORIAN_MIN_YEAR <= year <= _GREGORIAN_MAX_YEAR and 1 <= month <= 12
and 1 <= day <= _gregorian_days_in_month(year, month)):
raise ValueError(f"invalid Gregorian date: {year}-{month}-{day}")
a = (14 - month) // 12
y = year + 4800 - a
m = month + 12 * a - 3
jdn = day + (153 * m + 2) // 5 + 365 * y + y // 4 - y // 100 + y // 400 - 32045
_check_jdn(jdn)
return jdn
def jdn_to_gregorian(jdn):
"""Proleptic Gregorian (year, month, day) of a JDN."""
_check_jdn(jdn)
a = jdn + 32044
b = (4 * a + 3) // 146097
c = a - 146097 * b // 4
d = (4 * c + 3) // 1461
e = c - 1461 * d // 4
m = (5 * e + 2) // 153
return (100 * b + d - 4800 + m // 10,
m + 3 - 12 * (m // 10),
e - (153 * m + 2) // 5 + 1)
def to_gregorian(year, month, day):
return jdn_to_gregorian(to_jdn(year, month, day))
def from_gregorian(year, month, day):
return from_jdn(gregorian_to_jdn(year, month, day))
def day_of_week(year, month, day):
"""0 = Saturday (شنبه) ... 6 = Friday (جمعه)."""
return (to_jdn(year, month, day) + 2) % 7
def day_of_year(year, month, day):
"""1 ... 365/366."""
_check_date(year, month, day)
return _days_before_month(month) + day
if __name__ == "__main__":
import datetime
t = datetime.date.today()
y, m, d = from_gregorian(t.year, t.month, t.day)
print(f"{WEEKDAY_NAMES_FA[day_of_week(y, m, d)]} {d} {MONTH_NAMES_FA[m - 1]} {y}")Tests
test_persian_calendar.py
165 lines
PythonDownload
# Copyright (C) 2026 Goudarz Jafari <hi@goudarzjafari.com>
# SPDX-License-Identifier: MIT
"""Checks persian_calendar.py against the ground-truth data in /data.
Run: python -m unittest implementations/python/test_persian_calendar.py
"""
import csv
import os
import unittest
import persian_calendar as pc
DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "data")
def rows(name):
with open(os.path.join(DATA, name), encoding="utf-8") as f:
return [{k: int(v) if k != "nowruz_gregorian" else v for k, v in r.items()}
for r in csv.DictReader(f)]
class TestPersianCalendar(unittest.TestCase):
def test_years(self):
for r in rows("years.csv"):
y = r["year"]
self.assertEqual(pc.is_leap_year(y), r["is_leap"] == 1, y)
self.assertEqual(pc.days_in_month(y, 12), 30 if r["is_leap"] else 29, y)
gy, gm, gd = (int(x) for x in r["nowruz_gregorian"].split("-"))
self.assertEqual(pc.to_gregorian(y, 1, 1), (gy, gm, gd), y)
self.assertEqual(pc.to_jdn(y, 1, 1), r["nowruz_jdn"], y)
self.assertEqual(pc.day_of_week(y, 1, 1), r["nowruz_weekday"], y)
# every day of the year against the ground truth, both directions
for doy in range(r["days_in_year"]):
m, d = (doy // 31 + 1, doy % 31 + 1) if doy < 186 else ((doy - 186) // 30 + 7, (doy - 186) % 30 + 1)
jdn = r["nowruz_jdn"] + doy
if pc.from_jdn(jdn) != (y, m, d) or pc.to_jdn(y, m, d) != jdn:
self.fail(f"{y}/{m}/{d} (JDN {jdn})")
def test_vectors(self):
for r in rows("test-vectors.csv"):
p = (r["jy"], r["jm"], r["jd"])
g = (r["gy"], r["gm"], r["gd"])
self.assertEqual(pc.to_gregorian(*p), g, p)
self.assertEqual(pc.from_gregorian(*g), p, g)
self.assertEqual(pc.to_jdn(*p), r["jdn"], p)
self.assertEqual(pc.from_jdn(r["jdn"]), p, p)
self.assertEqual(pc.day_of_week(*p), r["weekday"], p)
def test_every_day_round_trip(self):
first = pc.to_jdn(pc.VERIFIED_MIN_YEAR, 1, 1)
last = pc.to_jdn(pc.VERIFIED_MAX_YEAR, 12, pc.days_in_month(pc.VERIFIED_MAX_YEAR, 12))
prev = pc.from_jdn(first - 1)
for jdn in range(first, last + 1):
y, m, d = pc.from_jdn(jdn)
self.assertTrue(pc.is_valid_date(y, m, d), jdn)
self.assertEqual(pc.to_jdn(y, m, d), jdn)
self.assertEqual(pc.gregorian_to_jdn(*pc.jdn_to_gregorian(jdn)), jdn)
# consecutive days: next day of month, or first day of next month/year
self.assertTrue((y, m, d - 1) == prev or (d == 1 and (
(y, m - 1) == prev[:2] or (m == 1 and prev[0] == y - 1 and prev[1] == 12))), jdn)
prev = (y, m, d)
def test_extrapolated_years(self):
# Outside 1178-3000 AP the calendar is an arithmetic extrapolation. Years <= 0 make
# intermediate values negative, which is exactly where truncating division breaks.
self.assertEqual(pc.to_jdn(-1000, 1, 1), 1582713)
self.assertEqual(pc.to_jdn(0, 1, 1), 1947955)
self.assertEqual(pc.to_jdn(4000, 1, 1), 3408925)
self.assertEqual(pc.from_jdn(0), (-5334, 9, 3))
self.assertEqual(pc.day_of_week(-1000, 1, 1), 1)
self.assertTrue(pc.is_leap_year(-3))
self.assertFalse(pc.is_leap_year(-1000))
for first_year, last_year in ((-1000, 1177), (3001, 4000)):
first = pc.to_jdn(first_year, 1, 1)
last = pc.to_jdn(last_year, 12, pc.days_in_month(last_year, 12))
prev = pc.from_jdn(first - 1)
for jdn in range(first, last + 1):
y, m, d = pc.from_jdn(jdn)
self.assertTrue(pc.is_valid_date(y, m, d), jdn)
self.assertEqual(pc.to_jdn(y, m, d), jdn)
self.assertEqual(pc.gregorian_to_jdn(*pc.jdn_to_gregorian(jdn)), jdn)
self.assertTrue((y, m, d - 1) == prev or (d == 1 and (
(y, m - 1) == prev[:2] or (m == 1 and prev[0] == y - 1 and prev[1] == 12))), jdn)
prev = (y, m, d)
def test_validation(self):
self.assertTrue(pc.is_valid_date(1403, 12, 30)) # leap year
self.assertFalse(pc.is_valid_date(1404, 12, 30)) # common year
self.assertTrue(pc.is_valid_date(1404, 6, 31))
self.assertFalse(pc.is_valid_date(1404, 7, 31))
self.assertFalse(pc.is_valid_date(1404, 13, 1))
self.assertFalse(pc.is_valid_date(1404, 0, 1))
self.assertFalse(pc.is_valid_date(1404, 1, 0))
self.assertFalse(pc.is_valid_date(1404, 1.5, 1)) # not an integer
self.assertFalse(pc.is_valid_date(1404, True, 1))
with self.assertRaises(ValueError):
pc.to_jdn(1404, 12, 30)
def test_limits_and_bad_input(self):
# The accepted range ends exactly at MIN_JDN / MAX_JDN.
self.assertEqual(pc.to_jdn(pc.MIN_YEAR, 1, 1), pc.MIN_JDN)
self.assertEqual(pc.to_jdn(pc.MAX_YEAR, 12, pc.days_in_month(pc.MAX_YEAR, 12)), pc.MAX_JDN)
self.assertEqual(pc.from_jdn(pc.MIN_JDN), (pc.MIN_YEAR, 1, 1))
self.assertEqual(pc.from_jdn(pc.MAX_JDN), (pc.MAX_YEAR, 12, 29))
self.assertEqual(pc.jdn_to_gregorian(pc.MIN_JDN), (-99379, 3, 29))
self.assertEqual(pc.jdn_to_gregorian(pc.MAX_JDN), (100622, 3, 13))
self.assertEqual(pc.gregorian_to_jdn(100622, 3, 13), pc.MAX_JDN)
for bad in (pc.MIN_JDN - 1, pc.MAX_JDN + 1, 2**63 - 1, -2**63, 10**100):
with self.assertRaises(ValueError):
pc.from_jdn(bad)
with self.assertRaises(ValueError):
pc.jdn_to_gregorian(bad)
for year in (pc.MIN_YEAR - 1, pc.MAX_YEAR + 1, 2**31):
self.assertFalse(pc.is_valid_date(year, 1, 1))
with self.assertRaises(ValueError):
pc.to_jdn(year, 1, 1)
with self.assertRaises(ValueError):
pc.is_leap_year(year)
with self.assertRaises(ValueError):
pc.gregorian_to_jdn(100622, 3, 14) # one day after MAX_JDN
# Invalid Gregorian dates are rejected, not silently normalized.
for bad in ((2025, 2, 29), (2025, 2, 30), (2025, 13, 1), (2025, 0, 1), (2025, 4, 31), (2025, 1, 0)):
with self.assertRaises(ValueError):
pc.gregorian_to_jdn(*bad)
with self.assertRaises(ValueError):
pc.from_gregorian(*bad)
self.assertEqual(pc.from_gregorian(2024, 2, 29), (1402, 12, 10)) # Gregorian leap day
# Non-integers raise TypeError.
for call in (lambda: pc.is_leap_year(1.5), lambda: pc.is_leap_year("1403"), lambda: pc.is_leap_year(True),
lambda: pc.days_in_month(1404, 6.5), lambda: pc.to_jdn(1404, 1.0, 1),
lambda: pc.from_jdn(2460756.5), lambda: pc.from_jdn("2460756"),
lambda: pc.gregorian_to_jdn(2025, 3, 21.0)):
with self.assertRaises(TypeError):
call()
def test_every_year_of_the_full_range(self):
# Every year MIN_YEAR..MAX_YEAR: years are contiguous, first and last day round-trip, and the
# leap years sit where every other implementation (and ICU 77.1+) puts them (checksums).
expected, leaps, nowruz_sum = pc.MIN_JDN, 0, 0
for y in range(pc.MIN_YEAR, pc.MAX_YEAR + 1):
nowruz = pc.to_jdn(y, 1, 1)
leap = pc.is_leap_year(y)
last = 30 if leap else 29
if (nowruz != expected or pc.from_jdn(nowruz) != (y, 1, 1)
or pc.days_in_month(y, 12) != last or pc.from_jdn(nowruz + 364 + leap) != (y, 12, last)):
self.fail(f"year {y}")
leaps += leap
nowruz_sum += nowruz
expected = nowruz + 365 + leap
self.assertEqual(expected - 1, pc.MAX_JDN)
self.assertEqual((leaps, nowruz_sum), (48_485, 389_592_978_180))
def test_known_dates(self):
self.assertEqual(pc.from_gregorian(2025, 3, 21), (1404, 1, 1))
self.assertEqual(pc.from_gregorian(2025, 3, 20), (1403, 12, 30))
self.assertEqual(pc.from_gregorian(1979, 2, 11), (1357, 11, 22))
self.assertEqual(pc.to_gregorian(1304, 1, 1), (1925, 3, 21))
self.assertEqual(pc.day_of_year(1404, 12, 29), 365)
self.assertEqual(pc.day_of_year(1404, 7, 1), 187)
self.assertEqual(pc.WEEKDAY_NAMES_EN[pc.day_of_week(1404, 1, 1)], "Friday")
if __name__ == "__main__":
unittest.main()