Skip to content
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

COMPAT: alias .to_numpy() for scalars #25142

Merged
merged 1 commit into from
Feb 16, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions doc/source/reference/arrays.rst
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ Methods
Timestamp.timetuple
Timestamp.timetz
Timestamp.to_datetime64
Timestamp.to_numpy
Timestamp.to_julian_date
Timestamp.to_period
Timestamp.to_pydatetime
Expand Down Expand Up @@ -191,6 +192,7 @@ Methods
Timedelta.round
Timedelta.to_pytimedelta
Timedelta.to_timedelta64
Timedelta.to_numpy
Timedelta.total_seconds

A collection of timedeltas may be stored in a :class:`TimedeltaArray`.
Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ Other API Changes
^^^^^^^^^^^^^^^^^

- :class:`DatetimeTZDtype` will now standardize pytz timezones to a common timezone instance (:issue:`24713`)
- ``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):
jreback marked this conversation as resolved.
Show resolved Hide resolved
"""
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):
Copy link
Contributor

Choose a reason for hiding this comment

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

same

"""
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
17 changes: 13 additions & 4 deletions pandas/tests/scalar/test_nat.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from pandas import (
DatetimeIndex, Index, NaT, Period, Series, Timedelta, TimedeltaIndex,
Timestamp)
Timestamp, isna)
from pandas.core.arrays import PeriodArray
from pandas.util import testing as tm

Expand Down 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 isna(expected) and isna(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 @@ -969,3 +969,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):
Copy link
Contributor

Choose a reason for hiding this comment

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

can you add a similar test in test_nat.py

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