Skip to content

Commit 9c9b148

Browse files
gh-161746: Use the Neri-Schneider algorithm for ordinal-to-date conversion in datetime (#161747)
Co-authored-by: Stan Ulbrych <stan@python.org>
1 parent 51e0ff0 commit 9c9b148

4 files changed

Lines changed: 84 additions & 136 deletions

File tree

‎Lib/_pydatetime.py‎

Lines changed: 23 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -90,67 +90,32 @@ def _ymd2ord(year, month, day):
9090
# pasting together 25 4-year cycles.
9191
assert _DI100Y == 25 * _DI4Y - 1
9292

93-
def _ord2ymd(n):
93+
def _ord2ymd(ordinal):
9494
"ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
9595

96-
# n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
97-
# repeats exactly every 400 years. The basic strategy is to find the
98-
# closest 400-year boundary at or before n, then work with the offset
99-
# from that boundary to n. Life is much clearer if we subtract 1 from
100-
# n first -- then the values of n at 400-year boundaries are exactly
101-
# those divisible by _DI400Y:
96+
# Neri and Schneider's algorithm, https://doi.org/10.1002/spe.3172.
97+
# ord_to_ymd() in Modules/_datetimemodule.c does the same steps.
10298
#
103-
# D M Y n n-1
104-
# -- --- ---- ---------- ----------------
105-
# 31 Dec -400 -_DI400Y -_DI400Y -1
106-
# 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
107-
# ...
108-
# 30 Dec 000 -1 -2
109-
# 31 Dec 000 0 -1
110-
# 1 Jan 001 1 0 400-year boundary
111-
# 2 Jan 001 2 1
112-
# 3 Jan 001 3 2
113-
# ...
114-
# 31 Dec 400 _DI400Y _DI400Y -1
115-
# 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
116-
n -= 1
117-
n400, n = divmod(n, _DI400Y)
118-
year = n400 * 400 + 1 # ..., -399, 1, 401, ...
119-
120-
# Now n is the (non-negative) offset, in days, from January 1 of year, to
121-
# the desired date. Now compute how many 100-year cycles precede n.
122-
# Note that it's possible for n100 to equal 4! In that case 4 full
123-
# 100-year cycles precede the desired day, which implies the desired
124-
# day is December 31 at the end of a 400-year cycle.
125-
n100, n = divmod(n, _DI100Y)
126-
127-
# Now compute how many 4-year cycles precede it.
128-
n4, n = divmod(n, _DI4Y)
129-
130-
# And now how many single years. Again n1 can be 4, and again meaning
131-
# that the desired day is December 31 at the end of the 4-year cycle.
132-
n1, n = divmod(n, 365)
133-
134-
year += n100 * 100 + n4 * 4 + n1
135-
if n1 == 4 or n100 == 4:
136-
assert n == 0
137-
return year-1, 12, 31
138-
139-
# Now the year is correct, and n is the offset from January 1. We find
140-
# the month via an estimate that's either exact or one too large.
141-
leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
142-
assert leapyear == _is_leap(year)
143-
month = (n + 50) >> 5
144-
preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
145-
if preceding > n: # estimate is too large
146-
month -= 1
147-
preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
148-
n -= preceding
149-
assert 0 <= n < _days_in_month(year, month)
150-
151-
# Now the year and month are correct, and n is the offset from the
152-
# start of that month: we're done!
153-
return year, month, n+1
99+
# Count days from 0000-03-01, so that the leap day is the last day of
100+
# its year. 0001-01-01 is day 306.
101+
days = ordinal + 305
102+
103+
# Centuries average _DI400Y/4 days: three of 36524, then one of 36525.
104+
century, rest = divmod(4 * days + 3, _DI400Y)
105+
day_of_century = rest // 4
106+
107+
# Likewise, years average _DI4Y/4 days: three of 365, then one of 366.
108+
year_of_century, rest = divmod(4 * day_of_century + 3, _DI4Y)
109+
day_of_year = rest // 4
110+
111+
# From March, month lengths repeat 31, 30, 31, 30, 31 (153 days).
112+
# 461 = 3*153 + 2 numbers the months from 3 (March) to 14 (February).
113+
month, rest = divmod(5 * day_of_year + 461, 153)
114+
day = rest // 5 + 1
115+
year = 100 * century + year_of_century
116+
if month > 12:
117+
return year + 1, month - 12, day
118+
return year, month, day
154119

155120
# Month and day names. For localized versions, see the calendar module.
156121
_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",

‎Lib/test/datetimetester.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1434,6 +1434,23 @@ def test_ordinal_conversions(self):
14341434
self.assertEqual(d, self.theclass.fromordinal(n))
14351435
n += 1
14361436

1437+
# Check the first and last days of every month in years at the
1438+
# start and the end of the 4-, 100- and 400-year cycles.
1439+
for year in (1, 3, 4, 5, 99, 100, 101, 399, 400, 401, 1899, 1900,
1440+
1901, 1999, 2001, 2100, 2399, 2400, 9996, 9999):
1441+
isleap = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
1442+
n = self.theclass(year, 1, 1).toordinal()
1443+
for month, maxday in zip(range(1, 13), dim):
1444+
if month == 2 and isleap:
1445+
maxday += 1
1446+
for day, ordinal in (1, n), (maxday, n + maxday - 1):
1447+
with self.subTest(year=year, month=month, day=day):
1448+
d = self.theclass(year, month, day)
1449+
self.assertEqual(d.toordinal(), ordinal)
1450+
self.assertEqual(d, self.theclass.fromordinal(ordinal))
1451+
n += maxday
1452+
self.assertEqual(n, self.theclass(year, 12, 31).toordinal() + 1)
1453+
14371454
def test_extreme_ordinals(self):
14381455
a = self.theclass.min
14391456
a = self.theclass(a.year, a.month, a.day) # get rid of time parts
@@ -1455,6 +1472,13 @@ def test_extreme_ordinals(self):
14551472

14561473
self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1))
14571474

1475+
# Past the maximum, the error still reports the year of the ordinal.
1476+
for n, year in ((aord + 1, 10000), (aord + 146097 + 1, 10400),
1477+
(2**31 - 1, 5879611)):
1478+
with self.subTest(n=n):
1479+
with self.assertRaisesRegex(ValueError, rf"\b{year}\b"):
1480+
self.theclass.fromordinal(n)
1481+
14581482
b = a - timedelta(days=1)
14591483
self.assertEqual(b.toordinal(), aord - 1)
14601484
self.assertEqual(b, self.theclass.fromordinal(aord - 1))
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Speed up :meth:`datetime.datetime.fromordinal` by about 15% (30% in the
2+
pure-Python implementation) by using the `Neri–Schneider algorithm
3+
<https://doi.org/10.1002/spe.3172>`__.

‎Modules/_datetimemodule.c‎

Lines changed: 34 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -471,88 +471,35 @@ days_before_month(int year, int month)
471471
#define DI100Y 36524 /* _PyTime_DaysBeforeYear(101); days in 100 years */
472472
#define DI400Y 146097 /* _PyTime_DaysBeforeYear(401); days in 400 years */
473473

474-
/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
474+
/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1.
475+
*
476+
* Neri and Schneider's algorithm, https://doi.org/10.1002/spe.3172; see
477+
* _ord2ymd() in Lib/_pydatetime.py for an explanation of the steps.
478+
*
479+
* The intermediate values only fit in 32 bits for small ordinals;
480+
* iso_to_ymd() passes the largest, MAXORDINAL + 2 (10000-01-02).
481+
*/
475482
static void
476483
ord_to_ymd(int ordinal, int *year, int *month, int *day)
477484
{
478-
int n, n1, n4, n100, n400, leapyear, preceding;
479-
480-
/* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
481-
* leap years repeats exactly every 400 years. The basic strategy is
482-
* to find the closest 400-year boundary at or before ordinal, then
483-
* work with the offset from that boundary to ordinal. Life is much
484-
* clearer if we subtract 1 from ordinal first -- then the values
485-
* of ordinal at 400-year boundaries are exactly those divisible
486-
* by DI400Y:
487-
*
488-
* D M Y n n-1
489-
* -- --- ---- ---------- ----------------
490-
* 31 Dec -400 -DI400Y -DI400Y -1
491-
* 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
492-
* ...
493-
* 30 Dec 000 -1 -2
494-
* 31 Dec 000 0 -1
495-
* 1 Jan 001 1 0 400-year boundary
496-
* 2 Jan 001 2 1
497-
* 3 Jan 001 3 2
498-
* ...
499-
* 31 Dec 400 DI400Y DI400Y -1
500-
* 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
501-
*/
502-
assert(ordinal >= 1);
503-
--ordinal;
504-
n400 = ordinal / DI400Y;
505-
n = ordinal % DI400Y;
506-
*year = n400 * 400 + 1;
507-
508-
/* Now n is the (non-negative) offset, in days, from January 1 of
509-
* year, to the desired date. Now compute how many 100-year cycles
510-
* precede n.
511-
* Note that it's possible for n100 to equal 4! In that case 4 full
512-
* 100-year cycles precede the desired day, which implies the
513-
* desired day is December 31 at the end of a 400-year cycle.
514-
*/
515-
n100 = n / DI100Y;
516-
n = n % DI100Y;
517-
518-
/* Now compute how many 4-year cycles precede it. */
519-
n4 = n / DI4Y;
520-
n = n % DI4Y;
521-
522-
/* And now how many single years. Again n1 can be 4, and again
523-
* meaning that the desired day is December 31 at the end of the
524-
* 4-year cycle.
525-
*/
526-
n1 = n / 365;
527-
n = n % 365;
528-
529-
*year += n100 * 100 + n4 * 4 + n1;
530-
if (n1 == 4 || n100 == 4) {
531-
assert(n == 0);
532-
*year -= 1;
533-
*month = 12;
534-
*day = 31;
535-
return;
485+
assert(1 <= ordinal && ordinal <= MAXORDINAL + 2);
486+
const uint32_t days = (uint32_t)ordinal + 305;
487+
const uint32_t century = (4 * days + 3) / DI400Y;
488+
const uint32_t day_of_century = (4 * days + 3) % DI400Y / 4;
489+
const uint32_t year_of_century = (4 * day_of_century + 3) / DI4Y;
490+
const uint32_t day_of_year = (4 * day_of_century + 3) % DI4Y / 4;
491+
const uint32_t m = (5 * day_of_year + 461) / 153;
492+
const uint32_t d = (5 * day_of_year + 461) % 153 / 5 + 1;
493+
const uint32_t y = 100 * century + year_of_century;
494+
if (m > 12) { /* January or February */
495+
*year = (int)(y + 1);
496+
*month = (int)(m - 12);
536497
}
537-
538-
/* Now the year is correct, and n is the offset from January 1. We
539-
* find the month via an estimate that's either exact or one too
540-
* large.
541-
*/
542-
leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
543-
assert(leapyear == is_leap(*year));
544-
*month = (n + 50) >> 5;
545-
preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
546-
if (preceding > n) {
547-
/* estimate is too large */
548-
*month -= 1;
549-
preceding -= days_in_month(*year, *month);
498+
else {
499+
*year = (int)y;
500+
*month = (int)m;
550501
}
551-
n -= preceding;
552-
assert(0 <= n);
553-
assert(n < days_in_month(*year, *month));
554-
555-
*day = n + 1;
502+
*day = (int)d;
556503
}
557504

558505
/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
@@ -3444,7 +3391,16 @@ datetime_date_fromordinal_impl(PyTypeObject *type, int ordinal)
34443391
PyErr_SetString(PyExc_ValueError, "ordinal must be >= 1");
34453392
return NULL;
34463393
}
3447-
ord_to_ymd(ordinal, &year, &month, &day);
3394+
if (ordinal <= MAXORDINAL) {
3395+
ord_to_ymd(ordinal, &year, &month, &day);
3396+
}
3397+
else {
3398+
/* Out of range, but compute the year for the error message.
3399+
* The calendar repeats every 400 years (DI400Y days). */
3400+
int cycles = (ordinal - 1) / DI400Y;
3401+
ord_to_ymd(ordinal - cycles * DI400Y, &year, &month, &day);
3402+
year += 400 * cycles;
3403+
}
34483404
return new_date_subclass_ex(year, month, day, type);
34493405
}
34503406

0 commit comments

Comments
 (0)