Skip to content
Open
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
3 changes: 2 additions & 1 deletion asv_bench/benchmarks/categoricals.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ def setup(self):
"int": np.random.randint(2**16, size=154),
"float": sys.maxsize * np.random.random((38,)),
"timestamp": [
pd.Timestamp(x, unit="s") for x in np.random.randint(2**18, size=578)
pd.Timestamp(x, input_unit="s")
for x in np.random.randint(2**18, size=578)
],
}

Expand Down
2 changes: 1 addition & 1 deletion asv_bench/benchmarks/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1134,7 +1134,7 @@ def setup(self):
index = MultiIndex.from_product(
[
np.arange(num_groups),
to_timedelta(np.arange(num_timedeltas), unit="s"),
to_timedelta(np.arange(num_timedeltas), input_unit="s"),
],
names=["groups", "timedeltas"],
)
Expand Down
18 changes: 9 additions & 9 deletions asv_bench/benchmarks/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,22 +118,22 @@ def setup(self):
# speed of int64, uint64 and float64 paths should be comparable

def time_nanosec_int64(self):
to_datetime(self.ts_nanosec, unit="ns")
to_datetime(self.ts_nanosec, input_unit="ns")

def time_nanosec_uint64(self):
to_datetime(self.ts_nanosec_uint, unit="ns")
to_datetime(self.ts_nanosec_uint, input_unit="ns")

def time_nanosec_float64(self):
to_datetime(self.ts_nanosec_float, unit="ns")
to_datetime(self.ts_nanosec_float, input_unit="ns")

def time_sec_uint64(self):
to_datetime(self.ts_sec_uint, unit="s")
to_datetime(self.ts_sec_uint, input_unit="s")

def time_sec_int64(self):
to_datetime(self.ts_sec, unit="s")
to_datetime(self.ts_sec, input_unit="s")

def time_sec_float64(self):
to_datetime(self.ts_sec_float, unit="s")
to_datetime(self.ts_sec_float, input_unit="s")


class ToDatetimeYYYYMMDD:
Expand Down Expand Up @@ -250,10 +250,10 @@ def setup(self, cache):
self.dup_string_with_tz = ["2000-02-11 15:00:00-0800"] * N

def time_unique_seconds_and_unit(self, cache):
to_datetime(self.unique_numeric_seconds, unit="s", cache=cache)
to_datetime(self.unique_numeric_seconds, input_unit="s", cache=cache)

def time_dup_seconds_and_unit(self, cache):
to_datetime(self.dup_numeric_seconds, unit="s", cache=cache)
to_datetime(self.dup_numeric_seconds, input_unit="s", cache=cache)

def time_dup_string_dates(self, cache):
to_datetime(self.dup_string_dates, cache=cache)
Expand All @@ -275,7 +275,7 @@ def setup(self):
self.str_seconds.append(f"00:00:{i:02d}")

def time_convert_int(self):
to_timedelta(self.ints, unit="s")
to_timedelta(self.ints, input_unit="s")

def time_convert_string_days(self):
to_timedelta(self.str_days)
Expand Down
4 changes: 2 additions & 2 deletions asv_bench/benchmarks/tslibs/timedelta.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ class TimedeltaConstructor:
def setup(self):
self.nptimedelta64 = np.timedelta64(3600)
self.dttimedelta = datetime.timedelta(seconds=3600)
self.td = Timedelta(3600, unit="s")
self.td = Timedelta(3600, input_unit="s")

def time_from_int(self):
Timedelta(123456789)

def time_from_unit(self):
Timedelta(1, unit="D")
Timedelta(1, input_unit="D")

def time_from_components(self):
Timedelta(
Expand Down
8 changes: 4 additions & 4 deletions doc/source/user_guide/timedeltas.rst
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ You can construct a ``Timedelta`` scalar through various arguments, including `I
pd.Timedelta(days=1, seconds=1)

# integers with a unit
pd.Timedelta(1, unit="D")
pd.Timedelta(1, input_unit="D")

# from a datetime.timedelta/np.timedelta64
pd.Timedelta(datetime.timedelta(days=1, seconds=1))
Expand Down Expand Up @@ -93,8 +93,8 @@ is numeric:

.. ipython:: python

pd.to_timedelta(np.arange(5), unit="s")
pd.to_timedelta(np.arange(5), unit="D")
pd.to_timedelta(np.arange(5), input_unit="s")
pd.to_timedelta(np.arange(5), input_unit="D")

.. warning::
If a string or array of strings is passed as an input then the ``unit`` keyword
Expand Down Expand Up @@ -199,7 +199,7 @@ You can fillna on timedeltas, passing a timedelta to get a particular value.
.. ipython:: python

y.fillna(pd.Timedelta(0))
y.fillna(pd.Timedelta(10, unit="s"))
y.fillna(pd.Timedelta(10, input_unit="s"))
y.fillna(pd.Timedelta("-1 days, 00:00:05"))

You can also negate, multiply and use ``abs`` on ``Timedeltas``:
Expand Down
20 changes: 10 additions & 10 deletions doc/source/user_guide/timeseries.rst
Original file line number Diff line number Diff line change
Expand Up @@ -307,25 +307,25 @@ Epoch timestamps
~~~~~~~~~~~~~~~~

pandas supports converting integer or float epoch times to ``Timestamp`` and
``DatetimeIndex``. The default unit is nanoseconds, since that is how ``Timestamp``
objects are stored internally. However, epochs are often stored in another ``unit``
``DatetimeIndex``. The default input_unit is nanoseconds, since that is how ``Timestamp``
objects are stored internally. However, epochs are often stored in another ``input_unit``
which can be specified. These are computed from the starting point specified by the
``origin`` parameter.

.. ipython:: python

pd.to_datetime(
[1349720105, 1349806505, 1349892905, 1349979305, 1350065705], unit="s"
[1349720105, 1349806505, 1349892905, 1349979305, 1350065705], input_unit="s"
)

pd.to_datetime(
[1349720105100, 1349720105200, 1349720105300, 1349720105400, 1349720105500],
unit="ms",
input_unit="ms",
)

.. note::

The ``unit`` parameter does not use the same strings as the ``format`` parameter
The ``input_unit`` parameter does not use the same strings as the ``format`` parameter
that was discussed :ref:`above<timeseries.converting.format>`. The
available units are listed on the documentation for :func:`pandas.to_datetime`.

Expand Down Expand Up @@ -353,8 +353,8 @@ as timezone-naive timestamps and then localize to the appropriate timezone:

.. ipython:: python

pd.to_datetime([1490195805.433, 1490195805.433502912], unit="s")
pd.to_datetime(1490195805433502912, unit="ns")
pd.to_datetime([1490195805.433, 1490195805.433502912], input_unit="s")
pd.to_datetime(1490195805433502912, input_unit="ns")

.. seealso::

Expand Down Expand Up @@ -389,14 +389,14 @@ of a ``DatetimeIndex``. For example, to use 1960-01-01 as the starting date:

.. ipython:: python

pd.to_datetime([1, 2, 3], unit="D", origin=pd.Timestamp("1960-01-01"))
pd.to_datetime([1, 2, 3], input_unit="D", origin=pd.Timestamp("1960-01-01"))

The default is set at ``origin='unix'``, which defaults to ``1970-01-01 00:00:00``.
Commonly called 'unix epoch' or POSIX time.

.. ipython:: python

pd.to_datetime([1, 2, 3], unit="D")
pd.to_datetime([1, 2, 3], input_unit="D")

.. _timeseries.daterange:

Expand Down Expand Up @@ -2633,7 +2633,7 @@ Transform nonexistent times to ``NaT`` or shift the times.
dti
dti.tz_localize("Europe/Warsaw", nonexistent="shift_forward")
dti.tz_localize("Europe/Warsaw", nonexistent="shift_backward")
dti.tz_localize("Europe/Warsaw", nonexistent=pd.Timedelta(1, unit="h"))
dti.tz_localize("Europe/Warsaw", nonexistent=pd.Timedelta(1, input_unit="h"))
dti.tz_localize("Europe/Warsaw", nonexistent="NaT")


Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,7 @@ Other Deprecations
- Deprecated allowing ``fill_value`` that cannot be held in the original dtype (excepting NA values for integer and bool dtypes) in :meth:`Series.unstack` and :meth:`DataFrame.unstack` (:issue:`12189`, :issue:`53868`)
- Deprecated allowing ``fill_value`` that cannot be held in the original dtype (excepting NA values for integer and bool dtypes) in :meth:`Series.shift` and :meth:`DataFrame.shift` (:issue:`53802`)
- Deprecated slicing on a :class:`Series` or :class:`DataFrame` with a :class:`DatetimeIndex` using a ``datetime.date`` object, explicitly cast to :class:`Timestamp` instead (:issue:`35830`)
- Deprecated the ``unit`` keyword in :meth:`to_datetime` and :meth:`to_timedelta`, use ``input_unit`` instead (:issue:`62097`)

.. ---------------------------------------------------------------------------
.. _whatsnew_300.prior_deprecations:
Expand Down
4 changes: 2 additions & 2 deletions pandas/_libs/tslibs/conversion.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def cast_from_unit_vectorized(
# but not clear what 2.5 "M" corresponds to, so we will
# disallow that case.
raise ValueError(
f"Conversion of non-round float with unit={unit} "
f"Conversion of non-round float with input_unit={unit} "
"is ambiguous"
)

Expand Down Expand Up @@ -194,7 +194,7 @@ cdef int64_t cast_from_unit(
# but not clear what 2.5 "M" corresponds to, so we will
# disallow that case.
raise ValueError(
f"Conversion of non-round float with unit={unit} "
f"Conversion of non-round float with input_unit={unit} "
"is ambiguous"
)
# GH#47266 go through np.datetime64 to avoid weird results e.g. with "Y"
Expand Down
2 changes: 1 addition & 1 deletion pandas/_libs/tslibs/offsets.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -5404,7 +5404,7 @@ cpdef to_offset(freq, bint is_period=False):
# For these prefixes, we have something like "3h" or
# "2.5min", so we can construct a Timedelta with the
# matching unit and get our offset from delta_to_tick
td = Timedelta(1, unit=name)
td = Timedelta(1, input_unit=name)
off = delta_to_tick(td)
offset = off * float(stride)
if n != 0:
Expand Down
2 changes: 2 additions & 0 deletions pandas/_libs/tslibs/timedeltas.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ class Timedelta(timedelta):
def __new__( # type: ignore[misc]
cls: type[Self],
value=...,
input_unit: str | None = ...,
*,
unit: str | None = ...,
**kwargs: float | np.integer | np.floating,
) -> Self | NaTType: ...
Expand Down
52 changes: 35 additions & 17 deletions pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1132,7 +1132,7 @@ cdef class _Timedelta(timedelta):

Examples
--------
>>> pd.Timedelta(1, "us").value
>>> pd.Timedelta(1, input_unit="us").value
1000
"""
try:
Expand Down Expand Up @@ -1174,7 +1174,7 @@ cdef class _Timedelta(timedelta):

Examples
--------
>>> td = pd.Timedelta(1, "d")
>>> td = pd.Timedelta(1, input_unit="d")
>>> td.days
1

Expand Down Expand Up @@ -1216,7 +1216,7 @@ cdef class _Timedelta(timedelta):

**Using integer input**

>>> td = pd.Timedelta(42, unit='s')
>>> td = pd.Timedelta(42, input_unit='s')
>>> td.seconds
42
"""
Expand Down Expand Up @@ -1256,7 +1256,7 @@ cdef class _Timedelta(timedelta):

**Using integer input**

>>> td = pd.Timedelta(42, unit='us')
>>> td = pd.Timedelta(42, input_unit='us')
>>> td.microseconds
42
"""
Expand Down Expand Up @@ -1308,7 +1308,8 @@ cdef class _Timedelta(timedelta):

Examples
--------
>>> td = pd.Timedelta(42, unit='us')
>>> td = pd.Timedelta(42, input_unit='us')
>>> td.unit
'ns'
"""
return npy_unit_to_abbrev(self._creso)
Expand Down Expand Up @@ -1652,7 +1653,7 @@ cdef class _Timedelta(timedelta):
>>> td.asm8
numpy.timedelta64(3005000,'ns')

>>> td = pd.Timedelta(42, unit='ns')
>>> td = pd.Timedelta(42, input_unit='ns')
>>> td.asm8
numpy.timedelta64(42,'ns')
"""
Expand Down Expand Up @@ -1696,7 +1697,7 @@ cdef class _Timedelta(timedelta):
>>> td.resolution_string
's'

>>> td = pd.Timedelta(36, unit='us')
>>> td = pd.Timedelta(36, input_unit='us')
>>> td.resolution_string
'us'
"""
Expand Down Expand Up @@ -1743,7 +1744,7 @@ cdef class _Timedelta(timedelta):

**Using integer input**

>>> td = pd.Timedelta(42, unit='ns')
>>> td = pd.Timedelta(42, input_unit='ns')
>>> td.nanoseconds
42
"""
Expand Down Expand Up @@ -1945,7 +1946,7 @@ class Timedelta(_Timedelta):
----------
value : Timedelta, timedelta, np.timedelta64, str, int or float
Input value.
unit : str, default 'ns'
input_unit : str, default 'ns'
If input is an integer, denote the unit of the input.
If input is a float, denote the unit of the integer parts.
The decimal parts with resolution lower than 1 nanosecond are ignored.
Expand All @@ -1965,6 +1966,10 @@ class Timedelta(_Timedelta):

Allowing the values `w`, `d`, `MIN`, `MS`, `US` and `NS` to denote units
are deprecated in favour of the values `W`, `D`, `min`, `ms`, `us` and `ns`.
unit : str or None, default None
Use input_unit instead.

.. deprecated:: 3.0.0

**kwargs
Available kwargs: {days, seconds, microseconds,
Expand Down Expand Up @@ -1995,7 +2000,7 @@ class Timedelta(_Timedelta):
--------
Here we initialize Timedelta object with both value and unit

>>> td = pd.Timedelta(1, "D")
>>> td = pd.Timedelta(1, input_unit="D")
>>> td
Timedelta('1 days 00:00:00')

Expand All @@ -2011,7 +2016,18 @@ class Timedelta(_Timedelta):
_req_any_kwargs_new = {"weeks", "days", "hours", "minutes", "seconds",
"milliseconds", "microseconds", "nanoseconds"}

def __new__(cls, object value=_no_input, unit=None, **kwargs):
def __new__(cls, object value=_no_input, input_unit=None, *, unit=None, **kwargs):
if unit is not None:
if input_unit is not None:
raise ValueError("Specify only 'input_unit', not 'unit'")
from pandas.errors import Pandas4Warning
warnings.warn(
"The 'unit' keyword is deprecated. Use 'input_unit' instead.",
Pandas4Warning,
stacklevel=find_stack_level(),
)
input_unit = unit

unsupported_kwargs = set(kwargs)
unsupported_kwargs.difference_update(cls._req_any_kwargs_new)
if unsupported_kwargs or (
Expand Down Expand Up @@ -2066,15 +2082,15 @@ class Timedelta(_Timedelta):
)
raise OutOfBoundsTimedelta(msg) from err

disallow_ambiguous_unit(unit)
disallow_ambiguous_unit(input_unit)

cdef:
int64_t new_value

# GH 30543 if pd.Timedelta already passed, return it
# check that only value is passed
if isinstance(value, _Timedelta):
# 'unit' is benign in this case, but e.g. days or seconds
# 'input_unit' is benign in this case, but e.g. days or seconds
# doesn't make sense here.
if len(kwargs):
# GH#48898
Expand All @@ -2085,8 +2101,10 @@ class Timedelta(_Timedelta):
)
return value
elif isinstance(value, str):
if unit is not None:
raise ValueError("unit must not be specified if the value is a str")
if input_unit is not None:
raise ValueError(
"input_unit must not be specified if the value is a str"
)
if (len(value) > 0 and value[0] == "P") or (
len(value) > 1 and value[:2] == "-P"
):
Expand Down Expand Up @@ -2143,8 +2161,8 @@ class Timedelta(_Timedelta):

elif is_integer_object(value) or is_float_object(value):
# unit=None is de-facto 'ns'
unit = parse_timedelta_unit(unit)
value = convert_to_timedelta64(value, unit)
input_unit = parse_timedelta_unit(input_unit)
value = convert_to_timedelta64(value, input_unit)
elif checknull_with_nat_and_na(value):
return NaT
else:
Expand Down
Loading
Loading