Skip to content

used regular expression in format_is_iso() #50468

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ Other enhancements
- :meth:`DataFrame.plot.hist` now recognizes ``xlabel`` and ``ylabel`` arguments (:issue:`49793`)
- Improved error message in :func:`to_datetime` for non-ISO8601 formats, informing users about the position of the first error (:issue:`50361`)
- Improved error message when trying to align :class:`DataFrame` objects (for example, in :func:`DataFrame.compare`) to clarify that "identically labelled" refers to both index and columns (:issue:`50083`)
- Performance improvement in :func:`to_datetime` when format is given or can be inferred (:issue:`50465`)
-

.. ---------------------------------------------------------------------------
Expand Down
26 changes: 18 additions & 8 deletions pandas/_libs/tslibs/strptime.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ from cpython.datetime cimport (
import_datetime()

from _thread import allocate_lock as _thread_allocate_lock
import re

import numpy as np
import pytz
Expand Down Expand Up @@ -50,6 +51,7 @@ from pandas._libs.util cimport (
is_float_object,
is_integer_object,
)

from pandas._libs.tslibs.timestamps import Timestamp

cnp.import_array()
Expand All @@ -60,15 +62,23 @@ cdef bint format_is_iso(f: str):
Generally of form YYYY-MM-DDTHH:MM:SS - date separator can be different
but must be consistent. Leading 0s in dates and times are optional.
"""
iso_regex = re.compile(
r"""
^ # start of string
%Y # Year
(?:([-/ \\.]?)%m # month with or without separators
(?: \1%d # day with same separator as for year-month
(?:[ T]%H # hour with separator
(?:\:%M # minute with separator
(?:\:%S # second with separator
(?:%z|\.%f(?:%z)? # timezone or fractional second
)?)?)?)?)?)? # optional
$ # end of string
""",
re.VERBOSE,
)
excluded_formats = ["%Y%m"]

for date_sep in [" ", "/", "\\", "-", ".", ""]:
for time_sep in [" ", "T"]:
for micro_or_tz in ["", "%z", ".%f", ".%f%z"]:
iso_fmt = f"%Y{date_sep}%m{date_sep}%d{time_sep}%H:%M:%S{micro_or_tz}"
if iso_fmt.startswith(f) and f not in excluded_formats:
return True
return False
return re.match(iso_regex, f) is not None and f not in excluded_formats


def _test_format_is_iso(f: str) -> bool:
Expand Down