Arithmetic Operations with Timedelta and DateOffset
Learn how to use the Timedelta and DateOffset functions to perform arithmetic operations.
Introduction
Part of working with time series data is applying math operations to it. Therefore, it’s important for us to understand the pandas capabilities that allow for precise and flexible date-time arithmetics. In particular, we’ll recap the Timedelta class before diving into DateOffset objects.
Basic operations with Timedelta
As a recap, the Timedelta class in pandas represents a difference between two dates or times, expressed in standard date time units (e.g., days, hours, and minutes), and can be positive or negative. The Timedelta is a powerful tool for working with time series data, because it allows us to perform arithmetic operations with time-based data. These arithmetic operations include adding or subtracting time intervals and calculating differences between dates.
Suppose we’re working with a DatetimeIndex with seconds precision, as illustrated below:
Sample DatetimeIndex with Seconds Resolution
Index |
2023-01-01 12:21:45 |
2023-01-02 07:30:30 |
2023-01-03 19:45:31 |
2023-01-04 16:44:03 |
In the following example, we use different functions to generate a variety of Timedelta objects before using them in arithmetic operations on the elements in the DatetimeIndex:
# Generate dummy DatetimeIndexdti = pd.DatetimeIndex(['2023-01-01 12:21:45','2023-01-02 07:30:30','2023-01-03 19:45:31','2023-01-04 16:44:03'])# Convert DatetimeIndex to DataFramedf = pd.DataFrame(index=dti)df.index.name = 'DatetimeIndex'# Option 1 - String representationtd1 = pd.Timedelta("1 days 12 hours")# Option 2 - Keyword argumentstd2 = pd.Timedelta(days=3, seconds=30)# Option 3 - Integer with unittd3 = pd.Timedelta(10, unit="D")# Addition of td1 (Add 1 day 12 hours)df['td1'] = df.index + td1# Subtraction of td2 (Subtract 3 days 30 seconds)df['td2'] = df.index - td2# Addition of td3 (Add 10 days)df['td3'] = df.index + td3# View outputprint(df)
From the output above, we can see that Timedelta objects make it easy for us to perform simple mathematics on Timestamp objects, which are within the DatetimeIndex in this case. A wide range of units is allowed for the frequency alias, thereby making Timedelta objects intuitive to work ...