You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf(converters): use fromisoformat fast path in convert_datetime - #1300
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)
```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.
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.
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: 4
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
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
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
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.
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
convert_datetime()currently runsDATETIME_RE.fullmatch(), builds a group list, pads fractional seconds, and converts each group tointon everyDATETIME/TIMESTAMPcolumn value.This adds a guarded fast path using CPython's C
datetime.datetime.fromisoformat()for standard MySQLYYYY-MM-DD[T]HH:MM:SS(len == 19) andYYYY-MM-DD[T]HH:MM:SS.f..ffffff(21 <= len <= 26) strings, falling back to the existingDATETIME_RE/convert_date()path for everything else.The guards (
-,:," "/"T",.,obj[11:13] != "24", anddt.tzinfo is None) preserve exactDATETIME_REsemantics across Python 3.9–3.14 (including rejecting comma fractions, timezone suffixes, week/compact ISO dates, >6 fractional digits, and Python 3.14's24:00:00midnight rollover).Benchmark (Python 3.14.10, best of 5 × 200k calls)
DATETIME(fsp=0)DATETIME(fsp=6)DATETIME(fsp=3)DATETIME(bytes)DATETIME, 100k rows)2026-12-03date-only)2007-2-5 3:6:21-digit)0000-00-00 00:00:00)Benchmark script
Summary by CodeRabbit
Tseparators and fractional seconds. Unsupported formats and invalid dates continue to use existing fallback behavior.