Open In App

Python | Pandas tseries.offsets.DateOffset

Last Updated : 26 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relative delta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specifies a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets can be created to move dates forward a given number of valid dates. For example, Bday(2) can be added to the date to move it two business days forward. If the date does not start on a valid date, first it is moved to a valid date and then offset is created.

Pandas tseries.offsets.DateOffset is used to create a standard kind of date increment used for a date range.

Python Pandas tseries.offsets.DateOffset Syntax

Below is the syntax by which we can use DateOffset objects in Pandas.

Syntax:
pandas.tseries.offsets.DateOffset(n=1, normalize=False, **kwds)

Parameters:

  • n : The number of time periods the offset represents.
  • normalize : Whether to round the result of a DateOffset addition down to the previous midnight.
  • level : int, str, default None
  • **kwds : Temporal parameter that adds to or replaces the offset value. Parameters that add to the offset (like Timedelta): years, months etc.

Returns : DateOffsets

Pandas tseries.offsets.DateOffset Examples

Below are the examples by which we can use Pandas tseries.offsets DateOffset objects in Pandas in Python:

Example 1: Create Dateoffsets of 2 Days

In this example, we will create DateOffsetss objects in Pandas of 2 days using pandas.tseries.offsets.DateOffset() function.

Python3




# importing pandas as pd
import pandas as pd
 
# Creating Timestamp
ts = pd.Timestamp('2019-10-10 07:15:11')
 
# Create the DateOffset
do = pd.tseries.offsets.DateOffset(n=2)
 
# Print the Timestamp
print(ts)
 
# Print the DateOffset
print(do)


Output :

2019-10-10 07:15:11
<2 * DateOffsets>

Now we will add the dateoffset to the given timestamp object to create an offset of 2 days from the given date. 

Python3




# Adding the dateoffset to the given timestamp
new_timestamp = ts + do
 
# Print the updated timestamp
print(new_timestamp)


Output :

2019-10-12 07:15:11

As we can see in the output, we have successfully created an offset of 2 days and added it to the given timestamp object to move the date forward by 2 days.

Example 2: Create DateOffsets of 10 Days and 2 Hours Using DateOffset Objects in Python

In this example, we will create DateOffsets of 10 Days and 2 Hours using DateOffset Objects in Python.

Python3




# importing pandas as pd
import pandas as pd
 
# Creating Timestamp
ts = pd.Timestamp('2019-10-10 07:15:11')
 
# Create the DateOffset
do = pd.tseries.offsets.DateOffset(days = 10, hours = 2)
 
# Print the Timestamp
print(ts)
 
# Print the DateOffset
print(do)


Output :

2019-10-10 07:15:11
<DateOffset: days=10, hours=2>

Now we will add the dateoffset to the given timestamp object to create an offset of 10 days and 2 hours from the given date. 

Python3




# Adding the dateoffset to the given timestamp
new_timestamp = ts + do
 
# Print the updated timestamp
print(new_timestamp)


Output :

2019-10-20 09:15:11

As we can see in the output, we have successfully created an offset of 10 days and 2 hours and added it to the given timestamp object to move the date forward by 10 days and 2 hours.

Example 3: Subtracting Months from a Date

In this example, a certain number of months are subtracted from a date using the DateOffset functionality.

Python3




import pandas as pd
 
date = pd.Timestamp('2023-12-22')
offset = pd.DateOffset(months=-2)
new_date = date + offset
print(new_date) 


Output:

Subtracting Months from a Date: 2023-10-22 00:00:00

Example 4: Applying the Offset to a Series

In this example, a sequence of dates is shifted forward or backward by a set number of days using the DateOffset mechanism.

Python3




import pandas as pd
 
dates = pd.date_range('2023-12-20', periods=5, freq='D')
offset = pd.DateOffset(days=3)
new_dates = dates + offset
print(new_dates)


Output:

Applying the Offset to a Series: 
DatetimeIndex(['2023-12-23', '2023-12-24', '2023-12-25', '2023-12-26',
'2023-12-27'],
dtype='datetime64[ns]', freq=None)

Example 5: Using Custom Frequency

In this example, a specific date is determined by adding a combination of weeks and days to a starting date using the DateOffset.

Python3




import pandas as pd
 
date = pd.Timestamp('2023-12-22')
# 2 weeks and 3 days
offset = pd.DateOffset(weeks=2, days=3
new_date = date + offset
print(new_date)


Output:

Using Custom Frequency: 2024-01-08 00:00:00


Previous Article
Next Article

Similar Reads

Python Pandas - DataFrame.copy() function
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. There are many ways to copy DataFrame in pandas. The first way is a simple way of assigning a dataframe object to a variable, but this h
2 min read
Python | Working with date and time using Pandas
While working with data, encountering time series data is very usual. Pandas is a very useful tool while working with time series data.  Pandas provide a different set of tools using which we can perform all the necessary tasks on date-time data. Let's try to understand with the examples discussed below. Working with Dates in PandasThe date class i
8 min read
Creating a Pandas DataFrame
In the real world, a Pandas DataFrame will be created by loading the datasets from existing storage, storage can be SQL Database, CSV file, and Excel file. Pandas DataFrame can be created from the lists, dictionary, and from a list of dictionary etc. A Dataframe is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows
3 min read
Boolean Indexing in Pandas
In boolean indexing, we will select subsets of data based on the actual values of the data in the DataFrame and not on their row/column labels or integer locations. In boolean indexing, we use a boolean vector to filter the data. Boolean indexing is a type of indexing that uses actual values of the data in the DataFrame. In boolean indexing, we can
6 min read
Pandas GroupBy
Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It's a simple concept but it's an extremely valuable technique that's widely used in data science. In real data science projects, you'll be dealing with large amounts of data and trying things over and over, so for efficiency, we use G
11 min read
Dealing with Rows and Columns in Pandas DataFrame
A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. We can perform basic operations on rows/columns like selecting, deleting, adding, and renaming. In this article, we are using nba.csv file. Dealing with Columns In order to deal with columns, we perform basic operations on columns like
5 min read
Apply a function to each row or column in Dataframe using pandas.apply()
Applying a function to a single or selected columns/rows in one go is a better way. For this we use the Pandas apply() function. There are different ways to apply a function to each row or column in Pandas DataFrame. We will learn about various ways to Apply Function to Every Row in this article. Creating a Sample DataFrameBefore seeing different w
7 min read
Global and Local Variables in Python
Python Global variables are those which are not defined inside any function and have a global scope whereas Python local variables are those which are defined inside a function and their scope is limited to that function only. In other words, we can say that local variables are accessible only inside the function in which it was initialized whereas
5 min read
Counters in Python | Set 2 (Accessing Counters)
Counters in Python | Set 1 (Initialization and Updation) Counters in Python | Set 2Once initialized, counters are accessed just like dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value's count is shown as 0. Example: In this example, we are using Counter to print the key and frequency of that key. The
2 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
4 min read
Article Tags :
Practice Tags :