Python Pandas - Check if the given DateOffset is Anchored


To check if the given DateOffset is Anchored, use the offset.is_anchored() method in Pandas. At first, import the required libraries −

from pandas.tseries.frequencies import to_offset
import pandas as pd

Set the timestamp object in Pandas −

timestamp = pd.Timestamp('2021-09-26 03:25:02.000045')

Create the DateOffset. We are using the Anchored offset i.e. weekly frequency here for Tuesday −

offset = to_offset("W-TUE")

Display the Updated Timestamp −

print("\nUpdated Timestamp...\n",timestamp + offset)

Check whether the DateOffset is anchored −

print("\nCheck whether the DateOffset is anchored...\n", offset.is_anchored())

Example

Following is the code −

from pandas.tseries.frequencies import to_offset
import pandas as pd

# Set the timestamp object in Pandas
timestamp = pd.Timestamp('2021-09-26 03:25:02.000045')

# Display the Timestamp
print("Timestamp...\n",timestamp)

# Create the DateOffset
# We are using the Anchored offset i.e. weekly frequency here for Tuesday
offset = to_offset("W-TUE")

# Display the DateOffset
print("\nDateOffset...\n",offset)

# Display the Updated Timestamp
print("\nUpdated Timestamp...\n",timestamp + offset)

# Check whether the DateOffset is anchored
print("\nCheck whether the DateOffset is anchored...\n", offset.is_anchored())

Output

This will produce the following code −

Timestamp...
 2021-09-26 03:25:02.000045

DateOffset...
 <Week: weekday=1>

Updated Timestamp...
 2021-09-28 03:25:02.000045

Check whether the DateOffset is anchored...
 True

Updated on: 21-Oct-2021

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements