Skip to content

Commit 953921f

Browse files
authored
BUG: to_datetime(format='...%f') parses nanoseconds (#48820)
1 parent 3368969 commit 953921f

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

doc/source/whatsnew/v1.5.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Fixed regressions
7676
- Fixed regression in :meth:`DataFrame.plot` ignoring invalid ``colormap`` for ``kind="scatter"`` (:issue:`48726`)
7777
- Fixed performance regression in :func:`factorize` when ``na_sentinel`` is not ``None`` and ``sort=False`` (:issue:`48620`)
7878
- Fixed regression causing an ``AttributeError`` during warning emitted if the provided table name in :meth:`DataFrame.to_sql` and the table name actually used in the database do not match (:issue:`48733`)
79+
- Fixed regression in :func:`to_datetime` when ``arg`` was a date string with nanosecond and ``format`` contained ``%f`` would raise a ``ValueError`` (:issue:`48767`)
7980
- Fixed :meth:`.DataFrameGroupBy.size` not returning a Series when ``axis=1`` (:issue:`48738`)
8081
- Fixed Regression in :meth:`DataFrameGroupBy.apply` when user defined function is called on an empty dataframe (:issue:`47985`)
8182

pandas/_libs/tslibs/strptime.pyx

+4-1
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ def array_strptime(ndarray[object] values, str fmt, bint exact=True, errors='rai
347347
"""
348348
TimeRE, _calc_julian_from_U_or_W are vendored
349349
from the standard library, see
350-
https://github.com/python/cpython/blob/master/Lib/_strptime.py
350+
https://github.com/python/cpython/blob/main/Lib/_strptime.py
351351
The original module-level docstring follows.
352352
353353
Strptime-related classes and functions.
@@ -383,6 +383,9 @@ class TimeRE(_TimeRE):
383383
"""
384384
self._Z = None
385385
super().__init__(locale_time=locale_time)
386+
# GH 48767: Overrides for cpython's TimeRE
387+
# 1) Parse up to nanos instead of micros
388+
self.update({"f": r"(?P<f>[0-9]{1,9})"}),
386389

387390
def __getitem__(self, key):
388391
if key == "Z":

pandas/tests/tools/test_to_datetime.py

+18
Original file line numberDiff line numberDiff line change
@@ -2815,3 +2815,21 @@ def test_to_datetime_cache_coerce_50_lines_outofbounds(series_length):
28152815

28162816
with pytest.raises(OutOfBoundsDatetime, match="Out of bounds nanosecond timestamp"):
28172817
to_datetime(s, errors="raise", utc=True)
2818+
2819+
2820+
def test_to_datetime_format_f_parse_nanos():
2821+
# GH 48767
2822+
timestamp = "15/02/2020 02:03:04.123456789"
2823+
timestamp_format = "%d/%m/%Y %H:%M:%S.%f"
2824+
result = to_datetime(timestamp, format=timestamp_format)
2825+
expected = Timestamp(
2826+
year=2020,
2827+
month=2,
2828+
day=15,
2829+
hour=2,
2830+
minute=3,
2831+
second=4,
2832+
microsecond=123456,
2833+
nanosecond=789,
2834+
)
2835+
assert result == expected

0 commit comments

Comments
 (0)