Skip to content

perf(converters): use fromisoformat fast path in convert_datetime - #1300

Open
gatewaytofredom wants to merge 1 commit into
PyMySQL:mainfrom
gatewaytofredom:perf/convert-datetime-fromisoformat
Open

gatewaytofredom wants to merge 1 commit into
PyMySQL:mainfrom
gatewaytofredom:perf/convert-datetime-fromisoformat

Conversation

@gatewaytofredom

@gatewaytofredom gatewaytofredom commented Dec 4, 2026 •

Copy link
Copy Markdown

convert_datetime() currently runs DATETIME_RE.fullmatch(), builds a group list, pads fractional seconds, and converts each group to int on every DATETIME/TIMESTAMPcolumn value.

This adds a guarded fast path using CPython's C datetime.datetime.fromisoformat() for standard MySQL YYYY-MM-DD[T]HH:MM:SS (len == 19) and YYYY-MM-DD[T]HH:MM:SS.f..ffffff (21 <= len <= 26) strings, falling back to the existing DATETIME_RE / convert_date() path for everything else.

The guards (-, :, " "/"T", ., obj[11:13] != "24", and dt.tzinfo is None) preserve exact DATETIME_RE semantics across Python 3.9–3.14 (including rejecting comma fractions, timezone suffixes, week/compact ISO dates, >6 fractional digits, and Python 3.14's 24:00:00 midnight rollover).

Benchmark (Python 3.14.10, best of 5 × 200k calls)

Case Before After Speedup
DATETIME (fsp=0) 191.3 ms 54.9 ms 3.49x
DATETIME (fsp=6) 217.3 ms 61.6 ms 3.53x
DATETIME (fsp=3) 221.8 ms 61.2 ms 3.63x
DATETIME (bytes) 195.6 ms 60.4 ms 3.24x
7-col row decode (5 scalar + 2 DATETIME, 100k rows) 403.1 ms 240.1 ms 1.68x
Fallback (2026-12-03 date-only) 110.8 ms 116.0 ms 0.96x
Fallback (2007-2-5 3:6:2 1-digit) 179.4 ms 186.7 ms 0.96x
Fallback (0000-00-00 00:00:00) 425.5 ms 529.0 ms 0.80x
Benchmark script
```python
import datetime
import timeit
from pymysql import converters
from pymysql.protocol import MysqlPacket

def convert_datetime_orig(obj):
    if isinstance(obj, (bytes, bytearray)):
        obj = obj.decode("ascii")
    m = converters.DATETIME_RE.fullmatch(obj)
    if not m:
        return converters.convert_date(obj)
    try:
        groups = list(m.groups())
        groups[-1] = converters._convert_second_fraction(groups[-1])
        return datetime.datetime(*[int(x) for x in groups])
    except ValueError: 
        return converters.convert_date(obj)

N = 200_000
for label, val in [
    ("fsp=0", "2026-12-03 19:15:30"),
    ("fsp=6", "2026-12-03 19:15:30.123456"),
    ("fsp=3", "2026-12-03 19:15:30.123"),
    ("bytes", b"2026-12-03 19:15:30"),
    ("date-only", "2026-12-03"),
    ("1-digit", "2007-2-5 3:6:2"),
    ("zero-date", "0000-00-00 00:00:00"), 
]:
    t1 = min(timeit.repeat(lambda v=val: convert_datetime_orig(v), number=N, repeat=5))
    t2 = min(timeit.repeat(lambda v=val: converters.convert_datetime(v), number=N, repeat=5)) 
    print(f"{label:12} {t1*1000:6.1f}ms -> {t2*1000:6.1f}ms ({t1/t2:.2f}x)")

Summary by CodeRabbit

  • Bug Fixes
    • Improved datetime conversion for ISO-style date and time strings, including T separators and fractional seconds. Unsupported formats and invalid dates continue to use existing fallback behavior.

@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

convert_datetime now tries datetime.fromisoformat for selected strings and continues to the existing conversion path when parsing fails or returns a timezone-aware value. New tests cover accepted and rejected datetime inputs.

Changes: Datetime conversion

Layer / File(s) Summary
ISO parsing and validation
pymysql/converters.py, pymysql/tests/test_converters.py
convert_datetime attempts ISO parsing for inputs that meet length, separator, and hour checks. It returns only naive datetimes and falls back to the existing conversion path otherwise. Tests cover accepted formats, invalid inputs, and fallback behavior.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Refactor

Possibly related PRs

  • PyMySQL/PyMySQL#1292: Changes convert_date, which is used by convert_datetime for inputs outside the new parsing path.
  • PyMySQL/PyMySQL#1287: Changes convert_date behavior on the fallback path used by convert_datetime.

Suggested reviewers: methane

Merge Risk: Minimal · up to a3f8d

This change speeds up parsing of standard datetime strings and keeps the existing behavior for other inputs through a fallback. No actionable merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: convert_datetime gains a fromisoformat fast path for performance. The raw summary confirms this change in pymysql/converters.py, with a matching edge-case test added. …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: convert_datetime gains a fromisoformat fast path for performance. The raw summary confirms this change in pymysql/converters.py, with a matching edge-case test added. The 'perf(converters)' prefix follows a conventional-commit style and is specific enough for a teammate scanning history.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ff10f628-2762-4a7d-84c7-2ed3b5886170
Commits

Reviewing files that changed from the base of the PR and between 7b9584f and a3f8d1b.

Files selected for processing: 2

  • pymysql/converters.py
  • pymysql/tests/test_converters.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant