Python Pandas - Timedelta



Timedelta in Pandas represents a duration, or the difference between two dates or times, expressed in units such as days, hours, minutes, or seconds. They are useful for performing arithmetic operations on datetime objects and can be both positive and negative duration's.

Pandas Timedelta Class

The pandas.Timedelta class is a powerful tool to represent a duration or the difference between two dates or times. It is equivalent of Python's datetime.timedelta object and can be used interchangeably in most cases.

Syntax

Following is the syntax of the class −

 class pandas.Timedelta(value=<object object>, unit=None, **kwargs) 

Where,

  • value − Accepts the any of the following time object: Timedelta, timedelta, np.timedelta64, str, or int.

  • unit − It is a optional parameter specifies the unit of the input if the input is an integer. Supported units include: 'W', 'D', 'days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds'.

  • **kwargs − Accepts keyword arguments like days, seconds, microseconds, milliseconds, minutes, hours, and weeks.

Example

Following is the basic example of creating the Timedelta object.

 import pandas as pd # Initialize Timedelta with value and unit td = pd.Timedelta(1, "d") print(td) print('Data Type of the Resultant Object:',type(td)) 

Following is the output of the above code −

 1 days 00:00:00 Data Type of the Resultant Object: <class 'pandas._libs.tslibs.timedeltas.Timedelta'> 

Also, you can create Timedelta objects in various ways, such as by passing a string, integer, or by using data offsets. Additionally, Pandas provides a top-level function to_timedelta() to convert scalar, array, list, or series into Timedelta type.

Creating Timedelta with a String

You can create a Timedelta object by passing a string that represents a duration.

Example

Here is the example of creating the Timedelta object using the string.

 import pandas as pd print(pd.Timedelta('2 days 2 hours 15 minutes 30 seconds')) 

Its output is as follows −

 2 days 02:15:30 

Creating Timedelta with an Integer

By passing an integer value with the unit, an argument creates a Timedelta object.

Example

This example converts an integer into the Timedelta object.

 import pandas as pd print(pd.Timedelta(6,unit='h')) 

Its output is as follows −

 0 days 06:00:00 

Creating Timedelta with Data Offsets

Data offsets such as - weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds can also be used in construction.

Example

Here is the example −

 import pandas as pd print(pd.Timedelta(days=2)) 

Its output is as follows −

Creating Timedelta with an Integer 2 days 00:00:00 

Using pd.to_timedelta() Function

The pd.to_timedelta function converts a scalar, array, list, or series from a recognized timedelta format or value into a Timedelta type. It will construct a Series if the input is a Series, a scalar if the input is scalar-like, or a TimedeltaIndex otherwise.

 import pandas as pd print(pd.Timedelta(days=2)) 

Its output is as follows −

 2 days 00:00:00 

Timedelta Operations

You can perform arithmetic operations on Series or DataFrames containing datetime64[ns] and timedelta64[ns] data types.

Example − Addition Operation

Let us now create a DataFrame with Timedelta and datetime objects and perform Addition operation on it −

 import pandas as pd s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D')) td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ]) df = pd.DataFrame(dict(A = s, B = td)) df['C']=df['A']+df['B'] print(df) 

Its output is as follows −

 A B C 0 2012-01-01 0 days 2012-01-01 1 2012-01-02 1 days 2012-01-03 2 2012-01-03 2 days 2012-01-05 

Example − Subtraction Operation

Here is the example of subtracting the Timedelta values.

 import pandas as pd s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D')) td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ]) df = pd.DataFrame(dict(A = s, B = td)) df['C']=df['A']+df['B'] df['D']=df['C']-df['B'] print(df) 

Its output is as follows −

 A B C D 0 2012-01-01 0 days 2012-01-01 2012-01-01 1 2012-01-02 1 days 2012-01-03 2012-01-04 2 2012-01-03 2 days 2012-01-05 2012-01-07 

Timedelta Class Properties and Methods

The Timedelta object provides various properties and methods that are useful in date-time manipulation.

Properties

Following are the list of attributes of the Timedelta object.

Sr.No.Property & Description
1

Timedelta.asm8

Return a numpy timedelta64 array scalar view.

2

Timedelta.components

Return a components namedtuple-like.

3

Timedelta.days

Returns the days of the timedelta.

4

Timedelta.max

Return the maximum timedelta object.

5

Timedelta.microseconds

Return the microseconds of the timedelta.

6

Timedelta.min

Return the minimum timedelta object.

7

Timedelta.nanoseconds

Return the number of nanoseconds (n), where 0 <= n < 1 microsecond.

8

Timedelta.resolution

Return the resolution of the timedelta.

9

Timedelta.seconds

Return the total hours, minutes, and seconds of the timedelta as seconds.

10

Timedelta.unit

Return the unit of the timedelta.

11

Timedelta.value

Return the underlying value of the timedelta in nanoseconds.

Methods

In the following table you can found the list of method of the Timedelta object.

Sr.No.Method & Description
1

Timedelta.as_unit(unit[, round_ok])

Convert the underlying int64 representation to the given unit.

2

Timedelta.ceil(freq)

Return a new Timedelta ceiled to this resolution.

3

Timedelta.floor(freq)

Return a new Timedelta floored to this resolution.

4

Timedelta.isoformat()

Format the Timedelta as ISO 8601 Duration.

5

Timedelta.round(freq)

Round the Timedelta to the specified resolution.

6

Timedelta.to_pytimedelta()

Convert a pandas Timedelta object into a python datetime.timedelta object.

7

Timedelta.to_timedelta64()

Return a numpy.timedelta64 object with 'ns' precision.

8

Timedelta.to_numpy([dtype, copy])

Convert the Timedelta to a NumPy timedelta64.

9

Timedelta.total_seconds()

Return the total seconds in the duration.

10

Timedelta.view(dtype)

Array view compatibility.

Advertisements
close