Skip to content

Commit 6854e79

Browse files
gh-158252: Add a C implementation for strptime (#158253)
Co-authored-by: Stan Ulbrych <stan@python.org>
1 parent ae5c457 commit 6854e79

13 files changed

Lines changed: 639 additions & 22 deletions

‎Doc/whatsnew/3.16.rst‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -983,6 +983,16 @@ zlib
983983
Optimizations
984984
=============
985985

986+
datetime and time
987+
-----------------
988+
989+
* :meth:`datetime.datetime.strptime`, :meth:`datetime.date.strptime`,
990+
:meth:`datetime.time.strptime`, and :func:`time.strptime` are faster
991+
for common numeric formats such as ``%Y-%m-%d`` and
992+
``%Y-%m-%d %H:%M:%S``.
993+
(Contributed by Paul Ganssle in :gh:`158252`, based on work by
994+
Stan Ulbrych.)
995+
986996
re
987997
--
988998

‎Include/internal/pycore_time.h‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,45 @@ extern PyTime_t _PyTimeFraction_Mul(
317317
extern double _PyTimeFraction_Resolution(
318318
const _PyTimeFraction *frac);
319319

320+
/* year -> number of days before January 1st of year. Remember that we
321+
* start with year 1, so days_before_year(1) == 0.
322+
*/
323+
static inline int
324+
_PyTime_DaysBeforeYear(int year)
325+
{
326+
int y = year - 1;
327+
/* This is incorrect if year <= 0; we really want the floor
328+
* here. But so long as MINYEAR is 1, the smallest year this
329+
* can see is 1.
330+
*/
331+
assert(year >= 1);
332+
return y*365 + y/4 - y/100 + y/400;
333+
}
334+
335+
// Weekday from a valid Gregorian year and 1-based day of year; Monday is 0.
336+
static inline int
337+
_PyTime_Weekday(int year, int yday)
338+
{
339+
return (_PyTime_DaysBeforeYear(year) + yday + 6) % 7;
340+
}
341+
342+
343+
// Locale-independent numeric strptime parsing.
344+
// A complete match returns 1; otherwise use Lib/_strptime.py. This function
345+
// neither allocates nor sets exceptions. The calendar date is validated, but
346+
// seconds may be 60 or 61: callers must apply their own time validation.
347+
typedef struct {
348+
int year, month, day;
349+
int hour, minute, second, fraction;
350+
int gmtoff; // INT_MIN means no offset was supplied.
351+
int yday; // January 1 is day 1.
352+
} _PyTime_StrptimeFields;
353+
354+
// Export for the '_datetime' shared extension.
355+
PyAPI_FUNC(int) _PyTime_Strptime(
356+
PyObject *string, PyObject *format, _PyTime_StrptimeFields *fields);
357+