Skip to content

Commit

Permalink
COMPAT: alias .to_numpy() for timestamp and timedelta scalars
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris Bertinato committed Feb 9, 2019
1 parent 2448e52 commit bb321a4
Show file tree
Hide file tree
Showing 7 changed files with 84 additions and 4 deletions.
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ Backwards incompatible API changes
Other API Changes
^^^^^^^^^^^^^^^^^

-
- ``Timestamp`` and ``Timedelta`` scalars now implement the :meth:`to_numpy` method as aliases to :meth:`Timestamp.to_datetime64` and :meth:`Timedelta.to_timedelta64`, respectively. (:issue:`24653`)

-
-

Expand Down
20 changes: 20 additions & 0 deletions pandas/_libs/tslibs/nattype.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,26 @@ cdef class _NaT(datetime):
"""
return np.datetime64('NaT', 'ns')

def to_numpy(self, dtype=None, copy=False):
"""
Convert the Timestamp to a NumPy datetime64.
.. versionadded:: 0.25.0
This is an alias method for `Timestamp.to_datetime64()`. The dtype and
copy parameters are available here only for compatibility. Their values
will not affect the return value.
Returns
-------
numpy.datetime64
See Also
--------
DatetimeIndex.to_numpy : Similar method for DatetimeIndex.
"""
return self.to_datetime64()

def __repr__(self):
return 'NaT'

Expand Down
20 changes: 20 additions & 0 deletions pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,26 @@ cdef class _Timedelta(timedelta):
""" Returns a numpy.timedelta64 object with 'ns' precision """
return np.timedelta64(self.value, 'ns')

def to_numpy(self, dtype=None, copy=False):
"""
Convert the Timestamp to a NumPy timedelta64.
.. versionadded:: 0.25.0
This is an alias method for `Timedelta.to_timedelta64()`. The dtype and
copy parameters are available here only for compatibility. Their values
will not affect the return value.
Returns
-------
numpy.timedelta64
See Also
--------
Series.to_numpy : Similar method for Series.
"""
return self.to_timedelta64()

def total_seconds(self):
"""
Total duration of timedelta in seconds (to ns precision)
Expand Down
20 changes: 20 additions & 0 deletions pandas/_libs/tslibs/timestamps.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,26 @@ cdef class _Timestamp(datetime):
"""
return np.datetime64(self.value, 'ns')

def to_numpy(self, dtype=None, copy=False):
"""
Convert the Timestamp to a NumPy datetime64.
.. versionadded:: 0.25.0
This is an alias method for `Timestamp.to_datetime64()`. The dtype and
copy parameters are available here only for compatibility. Their values
will not affect the return value.
Returns
-------
numpy.datetime64
See Also
--------
DatetimeIndex.to_numpy : Similar method for DatetimeIndex.
"""
return self.to_datetime64()

def __add__(self, other):
cdef:
int64_t other_int, nanos
Expand Down
15 changes: 12 additions & 3 deletions pandas/tests/scalar/test_nat.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,10 @@ def _get_overlap_public_nat_methods(klass, as_tuple=False):
"fromtimestamp", "isocalendar", "isoformat", "isoweekday",
"month_name", "now", "replace", "round", "strftime",
"strptime", "time", "timestamp", "timetuple", "timetz",
"to_datetime64", "to_pydatetime", "today", "toordinal",
"tz_convert", "tz_localize", "tzname", "utcfromtimestamp",
"utcnow", "utcoffset", "utctimetuple", "weekday"]),
"to_datetime64", "to_numpy", "to_pydatetime", "today",
"toordinal", "tz_convert", "tz_localize", "tzname",
"utcfromtimestamp", "utcnow", "utcoffset", "utctimetuple",
"weekday"]),
(Timedelta, ["total_seconds"])
])
def test_overlap_public_nat_methods(klass, expected):
Expand Down Expand Up @@ -339,3 +340,11 @@ def test_nat_arithmetic_td64_vector(op_name, box):
def test_nat_pinned_docstrings():
# see gh-17327
assert NaT.ctime.__doc__ == datetime.ctime.__doc__


def test_to_numpy_alias():
# GH 24653: alias .to_numpy() for scalars
expected = NaT.to_datetime64()
result = NaT.to_numpy()

assert np.isnat(expected) and np.isnat(result)
5 changes: 5 additions & 0 deletions pandas/tests/scalar/timedelta/test_timedelta.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,11 @@ def test_timedelta_conversions(self):
assert (Timedelta(timedelta(days=1)) ==
np.timedelta64(1, 'D').astype('m8[ns]'))

def test_to_numpy_alias(self):
# GH 24653: alias .to_numpy() for scalars
td = Timedelta('10m7s')
assert td.to_timedelta64() == td.to_numpy()

def test_round(self):

t1 = Timedelta('1 days 02:34:56.789123456')
Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/scalar/timestamp/test_timestamp.py
Original file line number Diff line number Diff line change
Expand Up @@ -962,3 +962,8 @@ def test_to_period_tz_warning(self):
with tm.assert_produces_warning(UserWarning):
# warning that timezone info will be lost
ts.to_period('D')

def test_to_numpy_alias(self):
# GH 24653: alias .to_numpy() for scalars
ts = Timestamp(datetime.now())
assert ts.to_datetime64() == ts.to_numpy()

0 comments on commit bb321a4

Please sign in to comment.