+

Python | Pandas tseries.offsets.DateOffset.rule_code

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.

tseries.offsets.DateOffset.rule_code Pandas tseries.offsets.DateOffset.rule_code returns the rule code applied to this DateOffset object. For example, the code for the BMonthEnd rule — "BM".

Syntax:
pandas.tseries.offsets.DateOffset.rule_code

Parameter: None

Returns: rule_code

Example # 1: Use the pandas.tseries attribute .offsets.DateOffset.rule_code to return the rule code applied to this DateOffset object.

# import pandas as pd

import pandas as pd

 
# import to_offset

from pandas.tseries.frequencies import to_offset

 
# Create a timestamp

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

  
# Create DateOffset 2 days

do = to_offset (freq = `2D ` )

  
# Print time stamp

print (ts)

 
# Print DateOffset

print (do)

Output:

Now we will add the dateoffset to this timestamp object to increase the datetime value. We will also return the rule code applied to the given DateOffset.

# Add dateoffset to this timestamp

new_timestamp = ts + do

 
# Print updated timestamp

print (new_timestamp)

 
# Now we will print the code for the rule
# for this DateOffset object

print (do.rule_code)

Output:

As we can see from the output, the attribute successfully returned the rule code applied to the given Dateoffset.

Example # 2: Use the pandas attribute .tseries.offsets.DateOffset.rule_code to return the rule code applied to this DateOffset object.

# import pandas as pd

import pandas as pd

  
# import to_offset

from pandas.tseries.frequencies import to_offset

  
# Create a timestamp

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

 
# Create DateOffset

do = to_offset (freq = `10D2H` )

  
# Print time stamp

print (ts)

 
# Print DateOffset

print (do)

Output:

We will now add a dateoffset to this timestamp object to increment the datetime value. We will also return the rule code applied to the given DateOffset.

# Add dateoffset to this timestamp

new_timestamp = ts + do

 
# Print updated timestamp

print (new_timestamp)

 
# Now we will print the code for the rule
# for this DateOffset object

print (do.rule_code)

Output:

As we can see from the output, the attribute successfully returned the rule code applied to the given Dateoffset object.

Get Solution for free from DataCamp guru