Skip to content

BUG: Fix nanosecond timedeltas #45108

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
Dec 31, 2021
Merged
Show file tree
Hide file tree
Changes from 6 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.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ Other enhancements
- :meth:`is_list_like` now identifies duck-arrays as list-like unless ``.ndim == 0`` (:issue:`35131`)
- :class:`ExtensionDtype` and :class:`ExtensionArray` are now (de)serialized when exporting a :class:`DataFrame` with :meth:`DataFrame.to_json` using ``orient='table'`` (:issue:`20612`, :issue:`44705`).
- Add support for `Zstandard <http://facebook.github.io/zstd/>`_ compression to :meth:`DataFrame.to_pickle`/:meth:`read_pickle` and friends (:issue:`43925`)
- :class:`Timedelta` now properly taking into account any nanoseconds contribution (:issue:`43764`)
-


Expand Down
32 changes: 25 additions & 7 deletions pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ cpdef int64_t delta_to_nanoseconds(delta) except? -1:
if PyDelta_Check(delta):
try:
return (
delta.days * 24 * 60 * 60 * 1_000_000
delta.days * 24 * 3600 * 1_000_000
+ delta.seconds * 1_000_000
+ delta.microseconds
) * 1000
Expand Down Expand Up @@ -1257,6 +1257,9 @@ class Timedelta(_Timedelta):
truncated to nanoseconds.
"""

_req_any_kwargs_new = {"weeks", "days", "hours", "minutes", "seconds",
"milliseconds", "microseconds", "nanoseconds"}

def __new__(cls, object value=_no_input, unit=None, **kwargs):
cdef _Timedelta td_base

Expand All @@ -1267,19 +1270,34 @@ class Timedelta(_Timedelta):
"(days,seconds....)")

kwargs = {key: _to_py_int_float(kwargs[key]) for key in kwargs}

nano = convert_to_timedelta64(kwargs.pop('nanoseconds', 0), 'ns')
try:
value = nano + convert_to_timedelta64(timedelta(**kwargs),
'ns')
except TypeError as e:
if not cls._req_any_kwargs_new.intersection(kwargs):
Copy link
Member

Choose a reason for hiding this comment

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

This change means we now fail to raise on pd.Timedelta(days=2, foo=9)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I am going to create a PR for this..

raise ValueError(
"cannot construct a Timedelta from the passed arguments, "
"allowed keywords are "
"[weeks, days, hours, minutes, seconds, "
"milliseconds, microseconds, nanoseconds]"
)

# GH43764, making sure any nanoseconds contributions from any kwarg
Copy link
Contributor

Choose a reason for hiding this comment

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

this is not a useful comment as its not relevant for a current reader. However a comment explaining what you are doing would be useful.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

# is taken into consideration
seconds = int((
(
(kwargs.get('days', 0) + kwargs.get('weeks', 0) * 7) * 24
+ kwargs.get('hours', 0)
) * 3600
+ kwargs.get('minutes', 0) * 60
+ kwargs.get('seconds', 0)
) * 1_000_000_000
)

value = convert_to_timedelta64(
Copy link
Contributor

Choose a reason for hiding this comment

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

let's just directly create a np.timedelta64(ts, "ns") no reason to go thru the routine when we know exactly what we have.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Nice. Oversaw that. Performance is even better now.

kwargs.get('nanoseconds', 0)
+ int(kwargs.get('microseconds', 0) * 1_000)
+ int(kwargs.get('milliseconds', 0) * 1_000_000)
+ seconds
, 'ns'
)

if unit in {'Y', 'y', 'M'}:
raise ValueError(
"Units 'M', 'Y', and 'y' are no longer supported, as they do not "
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/tslibs/test_timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@
(np.timedelta64(14, "D"), 14 * 24 * 3600 * 1e9),
(Timedelta(minutes=-7), -7 * 60 * 1e9),
(Timedelta(minutes=-7).to_pytimedelta(), -7 * 60 * 1e9),
(Timedelta(seconds=1234e-9), 1234), # GH43764, GH40946
(
Timedelta(seconds=1e-9, milliseconds=1e-5, microseconds=1e-1),
111,
), # GH43764
(
Timedelta(days=1, seconds=1e-9, milliseconds=1e-5, microseconds=1e-1),
24 * 3600e9 + 111,
), # GH43764
(offsets.Nano(125), 125),
(1, 1),
(np.int64(2), 2),
Expand Down