Python Pandas - Create a half-open time interval and check for existence of endpoints

To create a half-open time interval in Pandas, use pandas.Interval() with the closed parameter set to 'left'. A half-open interval includes the left endpoint but excludes the right endpoint, written as [0, 20).

Creating a Half-Open Interval

First, import the required library −

import pandas as pd

# Create a half-open interval [0, 20) where 0 <= x < 20
interval = pd.Interval(left=0, right=20, closed='left')
print("Interval:", interval)
print("Interval length:", interval.length)
Interval: [0, 20)
Interval length: 20

Checking Endpoint Existence

Use the in operator to check if endpoints exist in the interval −

import pandas as pd

interval = pd.Interval(left=0, right=20, closed='left')

# Check left endpoint (included in half-open left interval)
print("Left endpoint (0) in interval:", 0 in interval)

# Check right endpoint (excluded in half-open left interval)  
print("Right endpoint (20) in interval:", 20 in interval)

# Check a value within the interval
print("Value (10) in interval:", 10 in interval)
Left endpoint (0) in interval: True
Right endpoint (20) in interval: False
Value (10) in interval: True

Different Closed Parameters

Compare different interval types −

import pandas as pd

# Half-open left: [0, 20)
left_closed = pd.Interval(0, 20, closed='left')

# Half-open right: (0, 20]
right_closed = pd.Interval(0, 20, closed='right')

# Fully closed: [0, 20]
both_closed = pd.Interval(0, 20, closed='both')

print("Left-closed [0, 20):", left_closed)
print("Right-closed (0, 20]:", right_closed)
print("Both-closed [0, 20]:", both_closed)

print("\nEndpoint 0 inclusion:")
print("Left-closed:", 0 in left_closed)
print("Right-closed:", 0 in right_closed)
print("Both-closed:", 0 in both_closed)
Left-closed [0, 20): [0, 20)
Right-closed (0, 20]: (0, 20]
Both-closed [0, 20]: [0, 20]

Endpoint 0 inclusion:
Left-closed: True
Right-closed: False
Both-closed: True

Comparison

Closed Parameter Notation Left Endpoint Right Endpoint
'left' [0, 20) Included Excluded
'right' (0, 20] Excluded Included
'both' [0, 20] Included Included
'neither' (0, 20) Excluded Excluded

Conclusion

Half-open intervals with closed='left' include the left endpoint but exclude the right endpoint. Use the in operator to check endpoint existence and validate interval membership.

Updated on: 2026-03-26T17:49:06+05:30

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements