search
Search
Login
Math ML Join our weekly DS/ML newsletter
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
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
A
A
brightness_medium
share
arrow_backShare
Twitter
Facebook

Pandas | to_timedelta method

Pandas
chevron_right
Documentation
chevron_right
General Functions
schedule Jul 1, 2022
Last updated
local_offer PandasPython
Tags

Pandas to_timedelta(~) method converts the given argument into timedeltas. 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 timedeltas:

pd.to_timedelta([20,15], unit="hours")
TimedeltaIndex(['20:00:00', '15:00:00'], dtype='timedelta64[ns]', freq=None)

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 timedeltas

Timedeltas are 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)
mail
Join our newsletter for updates on new DS/ML comprehensive guides (spam-free)
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
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!