Pandas | to_timedelta method
Start your free 7-days trial now!
Pandas to_timedelta(~)
method converts the given argument into timedelta. Timedeltas are units of time (e.g. 1 hour, 40 milliseconds) that is used to perform arithmetics for dates.
Parameters
1. arg
link | string
or timedelta
or array-like
The data that is to be converted into a timedelta.
2. unit
link | string
| optional
The unit of the provided arg
. The possible values, taken directly from the official documentation, are as follows:
'Y', 'M', 'W', 'D', 'days', 'day', 'hours', 'hour', 'hr', 'h','m', 'minute', 'min', 'minutes', 'T', 'S', 'seconds', 'sec', 'second','ms', 'milliseconds', 'millisecond', 'milli', 'millis', 'L','us', 'microseconds', 'microsecond', 'micro', 'micros', 'U','ns', 'nanoseconds', 'nano', 'nanos', 'nanosecond', 'N'
By default, unit="ns"
(nanoseconds).
3. errors
link | string
| optional
How to handle cases when arg
cannot be converted into a timedelta:
Value | Description |
---|---|
| An error is raised if unable to parse |
| The |
| A |
By default, errors="raise"
.
Return Value
If a single unit of data is provided, then a timedelta64
is returned. Otherwise, a NumPy array of timedelta64
is returned.
Examples
From a string
To convert a string to a timedelta:
pd.to_timedelta("2 days 03:04:05")
Timedelta('2 days 03:04:05')
From an array of numbers
To convert an array of numbers to an array of timedelta
:
pd.to_timedelta([20,15], unit="hours")
TimedeltaIndex(['20:00:00', '15:00:00'], dtype='timedelta64[ns]', freq=None)
The decimals will be taken into account as well. For instance, consider the following:
pd.to_timedelta([2.5], unit="D")
TimedeltaIndex(['2 days 12:00:00'], dtype='timedelta64[ns]', freq=None)
We see that 2.5
days is interpreted as 2
days and 12
hours.
Handling errors
raise
By default, errors="raise"
- if any of the conversion is unsuccessful, an error is raised. For instance, suppose we have some non-sensical data like so:
pd.to_timedelta([20,[]], unit="hours") # errors="raise"
ValueError: Invalid type for timedelta scalar: <class 'list'>
ignore
Whenever a conversion from a specific value is unsuccessful, we can make the method return that value instead of throwing an error. This is done by setting unit="ignore"
:
pd.to_timedelta([20,[]], unit="hours", errors="ignore")
array([20, list([])], dtype=object)
coerce
For unsuccessful conversions, we can make the method return a NaT
(not-a-time) instead:
pd.to_timedelta([20,[]], unit="hours", errors="coerce")
TimedeltaIndex(['20:00:00', NaT], dtype='timedelta64[ns]', freq=None)
Practical use of timedelta
Timedelta
is primarily used to perform date arithmetic. For instance, you can apply an offset of 2 days to the dates in DatetimeIndex
like so:
idx = pd.DatetimeIndex(["2020-12-25","2020-12-26"])idx + pd.to_timedelta("2D")
DatetimeIndex(['2020-12-27', '2020-12-28'], dtype='datetime64[ns]', freq=None)
We can also add Timedelta
to a column of dates. For instance, consider the following:
df
A0 2020-12-251 2020-12-26
Let's add the some days to these dates:
df["B"] = df["A"] + pd.to_timedelta([3.5, 4], unit="D")df
A B0 2020-12-25 2020-12-28 12:00:001 2020-12-26 2020-12-30 00:00:00
Here, the resulting column B
is also datetime
:
df.dtypes
A datetime64[ns]B datetime64[ns]dtype: object