Skip to content

Commit be242d0

Browse files
Chris BertinatoPingviinituutti
Chris Bertinato
authored andcommitted
COMPAT: alias .to_numpy() for timestamp and timedelta scalars (pandas-dev#25142)
1 parent 873092d commit be242d0

File tree

8 files changed

+86
-4
lines changed

8 files changed

+86
-4
lines changed

doc/source/reference/arrays.rst

+2
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ Methods
120120
Timestamp.timetuple
121121
Timestamp.timetz
122122
Timestamp.to_datetime64
123+
Timestamp.to_numpy
123124
Timestamp.to_julian_date
124125
Timestamp.to_period
125126
Timestamp.to_pydatetime
@@ -191,6 +192,7 @@ Methods
191192
Timedelta.round
192193
Timedelta.to_pytimedelta
193194
Timedelta.to_timedelta64
195+
Timedelta.to_numpy
194196
Timedelta.total_seconds
195197

196198
A collection of timedeltas may be stored in a :class:`TimedeltaArray`.

doc/source/whatsnew/v0.25.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ Other API Changes
3434
^^^^^^^^^^^^^^^^^
3535

3636
- :class:`DatetimeTZDtype` will now standardize pytz timezones to a common timezone instance (:issue:`24713`)
37+
- ``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`)
3738
-
3839
-
3940

pandas/_libs/tslibs/nattype.pyx

+20
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,26 @@ cdef class _NaT(datetime):
188188
"""
189189
return np.datetime64('NaT', 'ns')
190190

191+
def to_numpy(self, dtype=None, copy=False):
192+
"""
193+
Convert the Timestamp to a NumPy datetime64.
194+
195+
.. versionadded:: 0.25.0
196+
197+
This is an alias method for `Timestamp.to_datetime64()`. The dtype and
198+
copy parameters are available here only for compatibility. Their values
199+
will not affect the return value.
200+
201+
Returns
202+
-------
203+
numpy.datetime64
204+
205+
See Also
206+
--------
207+
DatetimeIndex.to_numpy : Similar method for DatetimeIndex.
208+
"""
209+
return self.to_datetime64()
210+
191211
def __repr__(self):
192212
return 'NaT'
193213

pandas/_libs/tslibs/timedeltas.pyx

+20
Original file line numberDiff line numberDiff line change
@@ -824,6 +824,26 @@ cdef class _Timedelta(timedelta):
824824
""" Returns a numpy.timedelta64 object with 'ns' precision """
825825
return np.timedelta64(self.value, 'ns')
826826

827+
def to_numpy(self, dtype=None, copy=False):
828+
"""
829+
Convert the Timestamp to a NumPy timedelta64.
830+
831+
.. versionadded:: 0.25.0
832+
833+
This is an alias method for `Timedelta.to_timedelta64()`. The dtype and
834+
copy parameters are available here only for compatibility. Their values
835+
will not affect the return value.
836+
837+
Returns
838+
-------
839+
numpy.timedelta64
840+
841+
See Also
842+
--------
843+
Series.to_numpy : Similar method for Series.
844+
"""
845+
return self.to_timedelta64()
846+
827847
def total_seconds(self):
828848
"""
829849
Total duration of timedelta in seconds (to ns precision)

pandas/_libs/tslibs/timestamps.pyx

+20
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,26 @@ cdef class _Timestamp(datetime):
345345
"""
346346
return np.datetime64(self.value, 'ns')
347347

348+
def to_numpy(self, dtype=None, copy=False):
349+
"""
350+
Convert the Timestamp to a NumPy datetime64.
351+
352+
.. versionadded:: 0.25.0
353+
354+
This is an alias method for `Timestamp.to_datetime64()`. The dtype and
355+
copy parameters are available here only for compatibility. Their values
356+
will not affect the return value.
357+
358+
Returns
359+
-------
360+
numpy.datetime64
361+
362+
See Also
363+
--------
364+
DatetimeIndex.to_numpy : Similar method for DatetimeIndex.
365+
"""
366+
return self.to_datetime64()
367+
348368
def __add__(self, other):
349369
cdef:
350370
int64_t other_int, nanos

pandas/tests/scalar/test_nat.py

+13-4
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from pandas import (
1111
DatetimeIndex, Index, NaT, Period, Series, Timedelta, TimedeltaIndex,
12-
Timestamp)
12+
Timestamp, isna)
1313
from pandas.core.arrays import PeriodArray
1414
from pandas.util import testing as tm
1515

@@ -201,9 +201,10 @@ def _get_overlap_public_nat_methods(klass, as_tuple=False):
201201
"fromtimestamp", "isocalendar", "isoformat", "isoweekday",
202202
"month_name", "now", "replace", "round", "strftime",
203203
"strptime", "time", "timestamp", "timetuple", "timetz",
204-
"to_datetime64", "to_pydatetime", "today", "toordinal",
205-
"tz_convert", "tz_localize", "tzname", "utcfromtimestamp",
206-
"utcnow", "utcoffset", "utctimetuple", "weekday"]),
204+
"to_datetime64", "to_numpy", "to_pydatetime", "today",
205+
"toordinal", "tz_convert", "tz_localize", "tzname",
206+
"utcfromtimestamp", "utcnow", "utcoffset", "utctimetuple",
207+
"weekday"]),
207208
(Timedelta, ["total_seconds"])
208209
])
209210
def test_overlap_public_nat_methods(klass, expected):
@@ -339,3 +340,11 @@ def test_nat_arithmetic_td64_vector(op_name, box):
339340
def test_nat_pinned_docstrings():
340341
# see gh-17327
341342
assert NaT.ctime.__doc__ == datetime.ctime.__doc__
343+
344+
345+
def test_to_numpy_alias():
346+
# GH 24653: alias .to_numpy() for scalars
347+
expected = NaT.to_datetime64()
348+
result = NaT.to_numpy()
349+
350+
assert isna(expected) and isna(result)

pandas/tests/scalar/timedelta/test_timedelta.py

+5
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,11 @@ def test_timedelta_conversions(self):
414414
assert (Timedelta(timedelta(days=1)) ==
415415
np.timedelta64(1, 'D').astype('m8[ns]'))
416416

417+
def test_to_numpy_alias(self):
418+
# GH 24653: alias .to_numpy() for scalars
419+
td = Timedelta('10m7s')
420+
assert td.to_timedelta64() == td.to_numpy()
421+
417422
def test_round(self):
418423

419424
t1 = Timedelta('1 days 02:34:56.789123456')

pandas/tests/scalar/timestamp/test_timestamp.py

+5
Original file line numberDiff line numberDiff line change
@@ -969,3 +969,8 @@ def test_to_period_tz_warning(self):
969969
with tm.assert_produces_warning(UserWarning):
970970
# warning that timezone info will be lost
971971
ts.to_period('D')
972+
973+
def test_to_numpy_alias(self):
974+
# GH 24653: alias .to_numpy() for scalars
975+
ts = Timestamp(datetime.now())
976+
assert ts.to_datetime64() == ts.to_numpy()

0 commit comments

Comments
 (0)