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 | Timedelta constructor

schedule Aug 11, 2023
Last updated
local_offer
PythonPandas
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Pandas Timedelta(~) constructor creates a new Timedelta object, which represents a time difference in units that you specify. It is typically used to perform date arithmetics.

Examples

Initialising Timedelta

The following are time units offered by Pandas:

"Y", "M", "W", "D", "T", "S", "L", "U", or "N"
"days" or "day"
"hours", "hour", "hr", or "h"
"minutes", "minute", "min", or "m"
"seconds", "second", or "sec"
"milliseconds", "millisecond", "millis", or "milli"
"microseconds", "microsecond", "micros", or "micro"
"nanoseconds", "nanosecond", "nanos", "nano", or "ns".

A Timedelta of 2 days:

pd.Timedelta("2 days")
Timedelta('2 days 00:00:00')

Equivalently, specify keyword arguments:

pd.Timedelta(days=2)
Timedelta('2 days 00:00:00')

Equivalently, specify units:

pd.Timedelta(2, unit="days")
Timedelta('2 days 00:00:00')

A Timedelta of 2 days and 5 hours:

pd.Timedelta("2 days 5 hours")
Timedelta('2 days 05:00:00')

Equivalently, specify keyword arguments:

pd.Timedelta(days=2, hours=5)
Timedelta('2 days 05:00:00')

A negative Timedelta of 2 days:

pd.Timedelta("- 2 days")
Timedelta('-2 days +00:00:00')

A not-a-date Timedelta:

pd.Timedelta(None)
NaT

Date arithmetics

DatetimeIndex

Consider the following DatetimeIndex:

date_index = pd.date_range("2020-12-20","2020-12-21")
date_index
DatetimeIndex(['2020-12-20', '2020-12-21'], dtype='datetime64[ns]', freq='D')

Suppose we have the following Timedelta:

dt = pd.Timedelta("2 days")
dt
Timedelta('2 days 00:00:00')

Adding dt to our date_index applies an offset of 2 days:

date_index + dt
DatetimeIndex(['2020-12-22', '2020-12-23'], dtype='datetime64[ns]', freq=None)

To apply an offset of 2*2 days:

date_index + (2 * dt)
DatetimeIndex(['2020-12-24', '2020-12-25'], dtype='datetime64[ns]', freq=None)
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
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!