Pandas Timedelta

Python is the powerhouse of programming languages when it comes to data science. It has incredible tools and packages that make collecting, cleaning, and analyzing data more effortless and intuitive.

One such package is Pandas, which provides a robust set of tools for performing data analysis.

In this tutorial, we will discuss how to use the Timedelta class.

Pandas Timedelta

Timedelta represents the difference between two dates or times expressed in various duration units.

Pandas Timedelta is equivalent to the datetime.timedelta in native Python and can be used interchangeably in most cases.

The syntax is shown below:

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

The parameters are as shown:

  1. Value – Timedelta, np.timedelta64, string, and integer
  2. Unit – The unit of input. Possible input values include:
    1. “W”, “D”, “T”, “S”, “L”, “U”, or “N”
    2. “days” or “day”
    3. “hours”, “hour”, “hr”, or “h”
    4. “minutes”, “minute”, “min”, or “m”
    5. “seconds”, “second”, or “sec”
    6. “milliseconds”, “millisecond”, “millis”, or “milli”
    7. “microseconds”, “microsecond”, “micros”, or “micro”
    8. “nanoseconds”, “nanosecond”, “nanos”, “nano”, or “ns”

Let us illustrate how to use Timedelta with a few examples.

Example 1

Start by importing Pandas.

# import pandas
import pandas as pd

Next, we can create a Timedelta object from a string, as shown below:

to = pd.Timedelta('7 days 5 hours 34 minutes 33 seconds')

The previous code should return a Timedelta object, as shown below:

7 days 05:34:33

To fetch a specific unit from the Timedelta object, we can use the dot notation followed by the unit to extract.

For example, to extract the days attribute from the Timedelta object, we can run:


This should return the number of days, as shown below:


Example 2

You can also create a Timedelta object from an integer by passing an integer value and the unit as the parameters.

An example is shown below:

td_object = pd.Timedelta(560, unit='h')

The previous code creates a Timedelta object using an integer as the value as the hours as units.

This should return:

23 days 08:00:00


This article discussed how to use the Pandas Timedelta class to create Timedelta objects from various inputs. In addition, the parameters and examples were provided. Check other Linux Hint articles for more tips and tutorials.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list