<commit_before>.. currentmodule:: pandas
.. _timedeltas:

.. ipython:: python
   :suppress:

   from datetime import datetime, timedelta
   import numpy as np
   np.random.seed(123456)
   from pandas import *
   randn = np.random.randn
   randint = np.random.randint
   np.set_printoptions(precision=4, suppress=True)
   options.display.max_rows=15
   import dateutil
   import pytz
   from dateutil.relativedelta import relativedelta
   from pandas.tseries.api import *
   from pandas.tseries.offsets import *

.. _timedeltas.timedeltas:

***********
Time Deltas
***********

.. note::

   Starting in v0.15.0, we introduce a new scalar type ``Timedelta``, which is a subclass of ``datetime.timedelta``, and behaves in a similar manner,
   but allows compatibility with ``np.timedelta64`` types as well as a host of custom representation, parsing, and attributes.

Timedeltas are differences in times, expressed in difference units, e.g. days,hours,minutes,seconds.
They can be both positive and negative.

Parsing
-------

You can construct a ``Timedelta`` scalar thru various arguments:

.. ipython:: python

   # strings
   Timedelta('1 days')
   Timedelta('1 days 00:00:00')
   Timedelta('1 days 2 hours')
   Timedelta('-1 days 2 min 3us')

   # like datetime.timedelta
   # note: these MUST be specified as keyword argments
   Timedelta(days=1,seconds=1)

   # integers with a unit
   Timedelta(1,unit='d')

   # from a timedelta/np.timedelta64
   Timedelta(timedelta(days=1,seconds=1))
   Timedelta(np.timedelta64(1,'ms'))

   # negative Timedeltas have this string repr
   # to be more consistent with datetime.timedelta conventions
   Timedelta('-1us')

   # a NaT
   Timedelta('nan')
   Timedelta('nat')

:ref:`DateOffsets<timeseries.offsets>` (``Day, Hour, Minute, Second, Milli, Micro, Nano``) can also be used in construction.

.. ipython:: python

   Timedelta(Second(2))

Further, operations among the scalars yield another scalar ``Timedelta``

.. ipython:: python

   Timedelta(Day(2)) + Timedelta(Second(2)) + Timedelta('00:00:00.000123')

to_timedelta
~~~~~~~~~~~~

.. warning::

       Prior to 0.15.0 ``pd.to_timedelta`` would return a ``Series`` for list-like/Series input, and a ``np.timedelta64`` for scalar input.
       It will now return a ``TimedeltaIndex`` for list-like input, ``Series`` for Series input, and ``Timedelta`` for scalar input.

       The arguments to ``pd.to_timedelta`` are now ``(arg,unit='ns',box=True)``, previously were ``(arg,box=True,unit='ns')`` as these are more logical.

Using the top-level ``pd.to_timedelta``, you can convert a scalar, array, list, or Series from a recognized timedelta format / value into a ``Timedelta`` type.
It will construct Series if the input is a Series, a scalar if the input is scalar-like, otherwise will output a ``TimedeltaIndex``

.. ipython:: python

   to_timedelta('1 days 06:05:01.00003')
   to_timedelta('15.5us')
   to_timedelta(['1 days 06:05:01.00003','15.5us','nan'])
   to_timedelta(np.arange(5),unit='s')
   to_timedelta(np.arange(5),unit='d')

Operations
----------

You can operate on Series/DataFrames and construct ``timedelta64[ns]`` Series thru
subtraction operations on ``datetime64[ns]`` Series, or ``Timestamps``.

.. ipython:: python

   s = Series(date_range('2012-1-1', periods=3, freq='D'))
   td = Series([ Timedelta(days=i) for i in range(3) ])
   df = DataFrame(dict(A = s, B = td))
   df
   df['C'] = df['A'] + df['B']
   df
   df.dtypes

   s - s.max()
   s - datetime(2011,1,1,3,5)
   s + timedelta(minutes=5)
   s + Minute(5)
   s + Minute(5) + Milli(5)

Operations with scalars from a ``timedelta64[ns]`` series

.. ipython:: python

   y = s - s[0]
   y

Series of timedeltas with ``NaT`` values are supported

.. ipython:: python

   y = s - s.shift()
   y

Elements can be set to ``NaT`` using ``np.nan`` analogously to datetimes

.. ipython:: python

   y[1] = np.nan
   y

Operands can also appear in a reversed order (a singular object operated with a Series)

.. ipython:: python

   s.max() - s
   datetime(2011,1,1,3,5) - s
   timedelta(minutes=5) + s

``min, max`` and the corresponding ``idxmin, idxmax`` operations are supported on frames

.. ipython:: python

   A = s - Timestamp('20120101') - Timedelta('00:05:05')
   B = s - Series(date_range('2012-1-2', periods=3, freq='D'))

   df = DataFrame(dict(A=A, B=B))
   df

   df.min()
   df.min(axis=1)

   df.idxmin()
   df.idxmax()

``min, max, idxmin, idxmax`` operations are supported on Series as well. A scalar result will be a ``Timedelta``.

.. ipython:: python

   df.min().max()
   df.min(axis=1).min()

   df.min().idxmax()
   df.min(axis=1).idxmin()

You can fillna on timedeltas. Integers will be interpreted as seconds. You can
pass a timedelta to get a particular value.

.. ipython:: python

   y.fillna(0)
   y.fillna(10)
   y.fillna(Timedelta('-1 days, 00:00:05'))

You can also negate, multiply and use ``abs`` on  ``Timedeltas``

.. ipython:: python

   td1 = Timedelta('-1 days 2 hours 3 seconds')
   tdi
   -1 * td1
   - td1
   abs(td1)

.. _timedeltas.timedeltas_reductions:

Reductions
----------

Numeric reduction operation for ``timedelta64[ns]`` will return ``Timedelta`` objects. As usual<commit_msg>DOC: correction in timedelta.rst<commit_after>.. currentmodule:: pandas
.. _timedeltas:

.. ipython:: python
   :suppress:

   from datetime import datetime, timedelta
   import numpy as np
   np.random.seed(123456)
   from pandas import *
   randn = np.random.randn
   randint = np.random.randint
   np.set_printoptions(precision=4, suppress=True)
   options.display.max_rows=15
   import dateutil
   import pytz
   from dateutil.relativedelta import relativedelta
   from pandas.tseries.api import *
   from pandas.tseries.offsets import *

.. _timedeltas.timedeltas:

***********
Time Deltas
***********

.. note::

   Starting in v0.15.0, we introduce a new scalar type ``Timedelta``, which is a subclass of ``datetime.timedelta``, and behaves in a similar manner,
   but allows compatibility with ``np.timedelta64`` types as well as a host of custom representation, parsing, and attributes.

Timedeltas are differences in times, expressed in difference units, e.g. days,hours,minutes,seconds.
They can be both positive and negative.

Parsing
-------

You can construct a ``Timedelta`` scalar thru various arguments:

.. ipython:: python

   # strings
   Timedelta('1 days')
   Timedelta('1 days 00:00:00')
   Timedelta('1 days 2 hours')
   Timedelta('-1 days 2 min 3us')

   # like datetime.timedelta
   # note: these MUST be specified as keyword argments
   Timedelta(days=1,seconds=1)

   # integers with a unit
   Timedelta(1,unit='d')

   # from a timedelta/np.timedelta64
   Timedelta(timedelta(days=1,seconds=1))
   Timedelta(np.timedelta64(1,'ms'))

   # negative Timedeltas have this string repr
   # to be more consistent with datetime.timedelta conventions
   Timedelta('-1us')

   # a NaT
   Timedelta('nan')
   Timedelta('nat')

:ref:`DateOffsets<timeseries.offsets>` (``Day, Hour, Minute, Second, Milli, Micro, Nano``) can also be used in construction.

.. ipython:: python

   Timedelta(Second(2))

Further, operations among the scalars yield another scalar ``Timedelta``

.. ipython:: python

   Timedelta(Day(2)) + Timedelta(Second(2)) + Timedelta('00:00:00.000123')

to_timedelta
~~~~~~~~~~~~

.. warning::

       Prior to 0.15.0 ``pd.to_timedelta`` would return a ``Series`` for list-like/Series input, and a ``np.timedelta64`` for scalar input.
       It will now return a ``TimedeltaIndex`` for list-like input, ``Series`` for Series input, and ``Timedelta`` for scalar input.

       The arguments to ``pd.to_timedelta`` are now ``(arg,unit='ns',box=True)``, previously were ``(arg,box=True,unit='ns')`` as these are more logical.

Using the top-level ``pd.to_timedelta``, you can convert a scalar, array, list, or Series from a recognized timedelta format / value into a ``Timedelta`` type.
It will construct Series if the input is a Series, a scalar if the input is scalar-like, otherwise will output a ``TimedeltaIndex``

.. ipython:: python

   to_timedelta('1 days 06:05:01.00003')
   to_timedelta('15.5us')
   to_timedelta(['1 days 06:05:01.00003','15.5us','nan'])
   to_timedelta(np.arange(5),unit='s')
   to_timedelta(np.arange(5),unit='d')

Operations
----------

You can operate on Series/DataFrames and construct ``timedelta64[ns]`` Series thru
subtraction operations on ``datetime64[ns]`` Series, or ``Timestamps``.

.. ipython:: python

   s = Series(date_range('2012-1-1', periods=3, freq='D'))
   td = Series([ Timedelta(days=i) for i in range(3) ])
   df = DataFrame(dict(A = s, B = td))
   df
   df['C'] = df['A'] + df['B']
   df
   df.dtypes

   s - s.max()
   s - datetime(2011,1,1,3,5)
   s + timedelta(minutes=5)
   s + Minute(5)
   s + Minute(5) + Milli(5)

Operations with scalars from a ``timedelta64[ns]`` series

.. ipython:: python

   y = s - s[0]
   y

Series of timedeltas with ``NaT`` values are supported

.. ipython:: python

   y = s - s.shift()
   y

Elements can be set to ``NaT`` using ``np.nan`` analogously to datetimes

.. ipython:: python

   y[1] = np.nan
   y

Operands can also appear in a reversed order (a singular object operated with a Series)

.. ipython:: python

   s.max() - s
   datetime(2011,1,1,3,5) - s
   timedelta(minutes=5) + s

``min, max`` and the corresponding ``idxmin, idxmax`` operations are supported on frames

.. ipython:: python

   A = s - Timestamp('20120101') - Timedelta('00:05:05')
   B = s - Series(date_range('2012-1-2', periods=3, freq='D'))

   df = DataFrame(dict(A=A, B=B))
   df

   df.min()
   df.min(axis=1)

   df.idxmin()
   df.idxmax()

``min, max, idxmin, idxmax`` operations are supported on Series as well. A scalar result will be a ``Timedelta``.

.. ipython:: python

   df.min().max()
   df.min(axis=1).min()

   df.min().idxmax()
   df.min(axis=1).idxmin()

You can fillna on timedeltas. Integers will be interpreted as seconds. You can
pass a timedelta to get a particular value.

.. ipython:: python

   y.fillna(0)
   y.fillna(10)
   y.fillna(Timedelta('-1 days, 00:00:05'))

You can also negate, multiply and use ``abs`` on  ``Timedeltas``

.. ipython:: python

   td1 = Timedelta('-1 days 2 hours 3 seconds')
   td1
   -1 * td1
   - td1
   abs(td1)

.. _timedeltas.timedeltas_reductions:

Reductions
----------

Numeric reduction operation for ``timedelta64[ns]`` will return ``Timedelta`` objects. As usual
{'fraction_non_alphanumeric': 0.1443752991862135, 'fraction_numerical': 0.03322163714696027, 'mean_word_length': 3.6406041759218124, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3795929', 'n_tokens_mistral': 3887, 'n_tokens_neox': 3619, 'n_words': 1094}