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.
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:
The parameters are as shown:
- Value – Timedelta, np.timedelta64, string, and integer
- Unit – The unit of input. Possible input values include:
- “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”
Let us illustrate how to use Timedelta with a few examples.
Start by importing Pandas.
import pandas as pd
Next, we can create a Timedelta object from a string, as shown below:
The previous code should return a Timedelta object, as shown below:
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:
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:
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.