From 171d507b6711da4e62c1ec5b5743e122fd0029bc Mon Sep 17 00:00:00 2001 From: Brock Mendel Date: Thu, 28 May 2020 15:32:53 -0700 Subject: [PATCH] CLN: simplify to_offset --- pandas/_libs/tslibs/offsets.pyx | 32 +++---------------- .../tseries/frequencies/test_to_offset.py | 10 +----- 2 files changed, 6 insertions(+), 36 deletions(-) diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 30a1490fdf862..855fc014bfe7e 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -3532,16 +3532,6 @@ prefix_mapping = { ] } -_name_to_offset_map = { - "days": Day(1), - "hours": Hour(1), - "minutes": Minute(1), - "seconds": Second(1), - "milliseconds": Milli(1), - "microseconds": Micro(1), - "nanoseconds": Nano(1), -} - # hack to handle WOM-1MON opattern = re.compile( r"([+\-]?\d*|[+\-]?\d*\.\d*)\s*([A-Za-z]+([\-][\dA-Za-z\-]+)?)" @@ -3695,26 +3685,12 @@ cpdef to_offset(freq): delta = _get_offset(name) * stride elif isinstance(freq, timedelta): - from .timedeltas import Timedelta - - delta = None - freq = Timedelta(freq) - try: - for name in freq.components._fields: - offset = _name_to_offset_map[name] - stride = getattr(freq.components, name) - if stride != 0: - offset = stride * offset - if delta is None: - delta = offset - else: - delta = delta + offset - except ValueError as err: - raise ValueError(INVALID_FREQ_ERR_MSG.format(freq)) from err + return delta_to_tick(freq) - else: + elif isinstance(freq, str): delta = None stride_sign = None + try: split = re.split(opattern, freq) if split[-1] != "" and not split[-1].isspace(): @@ -3744,6 +3720,8 @@ cpdef to_offset(freq): delta = delta + offset except (ValueError, TypeError) as err: raise ValueError(INVALID_FREQ_ERR_MSG.format(freq)) from err + else: + delta = None if delta is None: raise ValueError(INVALID_FREQ_ERR_MSG.format(freq)) diff --git a/pandas/tests/tseries/frequencies/test_to_offset.py b/pandas/tests/tseries/frequencies/test_to_offset.py index beaefe9109e91..d3510eaa5c749 100644 --- a/pandas/tests/tseries/frequencies/test_to_offset.py +++ b/pandas/tests/tseries/frequencies/test_to_offset.py @@ -137,6 +137,7 @@ def test_to_offset_leading_plus(freqstr, expected): (dict(hours=1), offsets.Hour(1)), (dict(hours=1), frequencies.to_offset("60min")), (dict(microseconds=1), offsets.Micro(1)), + (dict(microseconds=0), offsets.Nano(0)), ], ) def test_to_offset_pd_timedelta(kwargs, expected): @@ -146,15 +147,6 @@ def test_to_offset_pd_timedelta(kwargs, expected): assert result == expected -def test_to_offset_pd_timedelta_invalid(): - # see gh-9064 - msg = "Invalid frequency: 0 days 00:00:00" - td = Timedelta(microseconds=0) - - with pytest.raises(ValueError, match=msg): - frequencies.to_offset(td) - - @pytest.mark.parametrize( "shortcut,expected", [