+

Python | Pandas tseries.offsets.DateOffset

DateOffsets can be created to move dates by a specified number of valid dates. For example, Bday (2) can be added to a date to move it two business days forward. If the date does not start with a valid date, it is first moved to a valid date and then an offset is generated.

Pandas tseries.offsets.DateOffset is used to create the standard date increment type used for the date range.

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

Parameter:
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 add to or replace the offset value. Parameters that add to the offset (like Timedelta): years, months etc.

Returns: DateOffsets

Example # 1 : Use the pandas.tseries.offsets.DateOffset function to create date offsets by 2 days.

# pandas import as pd

import pandas as pd

 
# Create a timestamp

ts = pd.Timestamp ( `2019-10-10 07: 15: 11` )

 
# Create DateOffset

do = pd.t series.offsets.DateOffset (n = 2 )

 
# Print time stamp

print (ts)

 
# Print DateOffset

print (do)

Output:

We will now add a date offset to this timestamp object to create an offset of 2 days from the specified date.

# Add dateoffset to data timestamp

new_timestamp = ts + do

 
# Print updated timestamp

print (new_timestamp )

Output:

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

Example # 2: Use the pandas.tseries.offsets.DateOffset function to create date offsets by 10 days and 2 hours.

# import pandas as pd

import pandas as pd

 
# Create a timestamp

ts = pd.Timestamp ( `2019-10-10 07: 15: 11` )

 
# Create DateOffset

do = pd.tseries.offsets.DateOffset (days = 10 , hours = 2 )

 
# Print time stamp

print (ts)

 
# Print DateOffset

print (do)

Output:

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

# Add dateoffset to this timestamp

new_timestamp = ts + do

  
# Print ь updated timestamp

print (new_timestamp)

Output:

As we can see from 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 for 10 days and 2 hours.

Get Solution for free from DataCamp guru