Python Pandas - Create a time interval and use Timestamps as the bounds


To create a time interval and use Timestamps as the bounds, use pandas.Interval and set timestamp within it using pandas.Timestamp.

At first, import the required libraries −

import pandas as pd

Use Timestamps as the bounds to create a time interval. Closed interval set using the "closed" parameter with value "left"

interval = pd.Interval(pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2021-01-01 00:00:00'), closed='left')

Above, we have used Timestamps as the bounds. Display the interval

print("Interval...\n",interval)

Example

Following is the code

import pandas as pd

# Use Timestamps as the bounds to create a time interval
# closed interval set using the "closed" parameter with value "left"
interval = pd.Interval(pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2021-01-01 00:00:00'), closed='left')

# display the interval
print("Interval...\n",interval)

# display the interval length
print("\nInterval length...\n",interval.length)

Output

This will produce the following code

Interval...
[2020-01-01, 2021-01-01)

Interval length...
366 days 00:00:00

Updated on: 20-Oct-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements