search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
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
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Pandas | to_timedelta method

schedule Aug 12, 2023
Last updated
local_offer
PandasPython
Tags
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. arglink | string or timedelta or array-like

The data that is to be converted into a timedelta.

2. unitlink | 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. errorslink | 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
A
0 2020-12-25
1 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 B
0 2020-12-25 2020-12-28 12:00:00
1 2020-12-26 2020-12-30 00:00:00

Here, the resulting column B is also datetime:

A datetime64[ns]
B datetime64[ns]
dtype: object
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
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!