search
Search
Unlock 100+ guides
search toc
close
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview Doc Search Code Search Beta SORRY NOTHING FOUND!
mic
Start speaking... Voice search is only supported in Safari and Chrome.
Shrink
Navigate to
check_circle
Mark as learned
thumb_up
0
thumb_down
0
chat_bubble_outline
0
Comment
auto_stories Bi-column layout
settings

# Pandas | to_timedelta method

schedule Aug 12, 2023
Last updated
local_offer
PandasPython
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
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

`"raise"`

An error is raised if unable to parse `arg`.

`"ignore"`

The `arg` itself will be returned if unable to be parsed.

`"coerce"`

A `NaT` (not-a-time) is returned if unable to parse `arg`.

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) ```
NOTE

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 = pd.DataFrame({"A": pd.date_range("2020-12-25", "2020-12-26")})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 ```
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!
{"ft_lang_label":"__label__en","ft_lang_prob":0.5049254,"math_prob":0.6480483,"size":3297,"snap":"2023-40-2023-50","text_gpt3_token_len":982,"char_repetition_ratio":0.14788947,"word_repetition_ratio":0.013824885,"special_character_ratio":0.33242342,"punctuation_ratio":0.2106782,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9563414,"pos_list":[0,1,2,3,4,5,6,7,8],"im_url_duplicate_count":[null,null,null,null,null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-11-28T12:41:21Z\",\"WARC-Record-ID\":\"<urn:uuid:1bb9ac29-42d3-4f9a-b800-ce5815b9f529>\",\"Content-Length\":\"44940\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:c9cafb5b-ac88-45b1-9429-c27d5e1bcc1a>\",\"WARC-Concurrent-To\":\"<urn:uuid:cb7b2317-13c5-4c84-86ad-8ae648d48ad0>\",\"WARC-IP-Address\":\"104.21.49.18\",\"WARC-Target-URI\":\"https://www.skytowner.com/explore/pandas_to_timedelta_method\",\"WARC-Payload-Digest\":\"sha1:QFD5KLZD45XWQSEG4HJDRWYBTZNB3R55\",\"WARC-Block-Digest\":\"sha1:6ON7W2GVAOVG6UZFK4XQI5AJNZS2Q4S4\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-50/CC-MAIN-2023-50_segments_1700679099514.72_warc_CC-MAIN-20231128115347-20231128145347-00130.warc.gz\"}"}