Skip to content

ENH: Enable parsing of ISO8601-like timestamps with negative signs using pd.Timedelta (GH37172) #39497

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 7 commits into from
Feb 10, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ Other enhancements
- :meth:`DataFrame.plot.scatter` can now accept a categorical column as the argument to ``c`` (:issue:`12380`, :issue:`31357`)
- :meth:`.Styler.set_tooltips` allows on hover tooltips to be added to styled HTML dataframes.
- :meth:`Series.loc.__getitem__` and :meth:`Series.loc.__setitem__` with :class:`MultiIndex` now raising helpful error message when indexer has too many dimensions (:issue:`35349`)
- Add support for parsing ISO8601-like timestamps with negative signs to :meth:`pandas.Timedelta` (:issue:`37172`)

.. ---------------------------------------------------------------------------

Expand Down
20 changes: 14 additions & 6 deletions pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ cdef convert_to_timedelta64(object ts, str unit):
ts = cast_from_unit(ts, unit)
ts = np.timedelta64(ts, "ns")
elif isinstance(ts, str):
if len(ts) > 0 and ts[0] == "P":
if len(ts) > 0 and (ts[0] == "P" or ts[:2] == "-P"):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you need another length check here (e.g. if len(ts) ==1 this would raise)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated

ts = parse_iso_format_string(ts)
else:
ts = parse_timedelta_string(ts)
Expand Down Expand Up @@ -672,18 +672,23 @@ cdef inline int64_t parse_iso_format_string(str ts) except? -1:
cdef:
unicode c
int64_t result = 0, r
int p = 0
int p = 0, sign = 1
object dec_unit = 'ms', err_msg
bint have_dot = 0, have_value = 0, neg = 0
bint have_dot = 0, have_value = 0, neg = 0, valid_ts = 0
list number = [], unit = []

err_msg = f"Invalid ISO 8601 Duration format - {ts}"

if ts[0] == "-":
sign = -1
ts = ts[1:]

for c in ts:
# number (ascii codes)
if 48 <= ord(c) <= 57:

have_value = 1
valid_ts = 1
if have_dot:
if p == 3 and dec_unit != 'ns':
unit.append(dec_unit)
Expand All @@ -703,13 +708,16 @@ cdef inline int64_t parse_iso_format_string(str ts) except? -1:
neg = 0
unit, number = [], [c]
else:
have_value = 0
if c == 'P' or c == 'T':
pass # ignore marking characters P and T
elif c == '-':
if neg or have_value:
raise ValueError(err_msg)
else:
neg = 1
elif c == "+":
pass
elif c in ['W', 'D', 'H', 'M']:
if c in ['H', 'M'] and len(number) > 2:
raise ValueError(err_msg)
Expand Down Expand Up @@ -746,11 +754,11 @@ cdef inline int64_t parse_iso_format_string(str ts) except? -1:
else:
raise ValueError(err_msg)

if not have_value:
if not valid_ts:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you cannot use have_value or maybe have_value && sign? adding this makes harder to understand

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have_value alone was sufficient

# Received string only - never parsed any values
raise ValueError(err_msg)

return result
return sign*result


cdef _to_py_int_float(v):
Expand Down Expand Up @@ -1251,7 +1259,7 @@ class Timedelta(_Timedelta):
elif isinstance(value, str):
if unit is not None:
raise ValueError("unit must not be specified if the value is a str")
if len(value) > 0 and value[0] == 'P':
if len(value) > 0 and (value[0] == 'P' or value[:2] == "-P"):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same comment as above

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated

value = parse_iso_format_string(value)
else:
value = parse_timedelta_string(value)
Expand Down
3 changes: 3 additions & 0 deletions pandas/tests/scalar/timedelta/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,9 @@ def test_construction_out_of_bounds_td64():
("P1W", Timedelta(days=7)),
("PT300S", Timedelta(seconds=300)),
("P1DT0H0M00000000000S", Timedelta(days=1)),
("PT-6H3M", Timedelta(hours=-6, minutes=3)),
("-PT6H3M", Timedelta(hours=-6, minutes=-3)),
("-PT-6H+3M", Timedelta(hours=6, minutes=-3)),
],
)
def test_iso_constructor(fmt, exp):
Expand Down