Skip to content

Commit 579e070

Browse files
authored
BUG: Period constructor raises instead of ignoring when passing a string with extra precision(pico, femto, etc.) (#50417)
* TST: Add test for Period construction from str with zero nanos * BUG: Period would raise a KeyError when given a string with extra precision * Update parsing.pyx
1 parent 9e5a62f commit 579e070

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

doc/source/whatsnew/v2.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -1021,7 +1021,7 @@ Period
10211021
^^^^^^
10221022
- Bug in :meth:`Period.strftime` and :meth:`PeriodIndex.strftime`, raising ``UnicodeDecodeError`` when a locale-specific directive was passed (:issue:`46319`)
10231023
- Bug in adding a :class:`Period` object to an array of :class:`DateOffset` objects incorrectly raising ``TypeError`` (:issue:`50162`)
1024-
-
1024+
- Bug in :class:`Period` where passing a string with finer resolution than nanosecond would result in a ``KeyError`` instead of dropping the extra precision (:issue:`50417`)
10251025

10261026
Plotting
10271027
^^^^^^^^

pandas/_libs/tslibs/parsing.pyx

+8-1
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ def parse_datetime_string_with_reso(
377377
&out_tzoffset, False
378378
)
379379
if not string_to_dts_failed:
380-
if dts.ps != 0 or out_local:
380+
if out_bestunit == NPY_DATETIMEUNIT.NPY_FR_ns or out_local:
381381
# TODO: the not-out_local case we could do without Timestamp;
382382
# avoid circular import
383383
from pandas import Timestamp
@@ -386,6 +386,13 @@ def parse_datetime_string_with_reso(
386386
parsed = datetime(
387387
dts.year, dts.month, dts.day, dts.hour, dts.min, dts.sec, dts.us
388388
)
389+
# Match Timestamp and drop picoseconds, femtoseconds, attoseconds
390+
# The new resolution will just be nano
391+
# GH 50417
392+
if out_bestunit in {NPY_DATETIMEUNIT.NPY_FR_ps,
393+
NPY_DATETIMEUNIT.NPY_FR_fs,
394+
NPY_DATETIMEUNIT.NPY_FR_as}:
395+
out_bestunit = NPY_DATETIMEUNIT.NPY_FR_ns
389396
reso = {
390397
NPY_DATETIMEUNIT.NPY_FR_Y: "year",
391398
NPY_DATETIMEUNIT.NPY_FR_M: "month",

pandas/tests/scalar/period/test_period.py

+5
Original file line numberDiff line numberDiff line change
@@ -545,6 +545,11 @@ def test_period_cons_combined(self):
545545
(".000000999", 999),
546546
(".123456789", 789),
547547
(".999999999", 999),
548+
(".999999000", 0),
549+
# Test femtoseconds, attoseconds, picoseconds are dropped like Timestamp
550+
(".999999001123", 1),
551+
(".999999001123456", 1),
552+
(".999999001123456789", 1),
548553
],
549554
)
550555
def test_period_constructor_nanosecond(self, day, hour, sec_float, expected):

0 commit comments

Comments
 (0)