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

PythonServer Side ProgrammingProgramming

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
raja
Updated on 20-Oct-2021 07:04:24

Advertisements