Pandas
keyboard_arrow_down 655 guides
chevron_leftDatetimes
check_circle
Mark as learned thumb_up
1
thumb_down
0
chat_bubble_outline
0
Comment auto_stories Bi-column layout
settings
Pandas | Timedelta constructor
schedule Aug 11, 2023
Last updated local_offer
Tags Python●Pandas
tocTable of Contents
expand_more Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!
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)
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...
Official Pandas Documentation
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timedelta.html
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!