Working with Periods
The Period
class is a fundamental component of the Time Series Package, representing time intervals used for
various operations.
Understanding Periods
A Period
represents a fixed interval of time, such as:
One year (
P1Y
)One month (
P1M
)One day (
P1D
)One hour (
PT1H
)15 minutes (
PT15M
)
Periods serve several purposes:
Defining the resolution of timestamps in a TimeSeries
Defining the periodicity of data points in a TimeSeries
Specifying time intervals for aggregation
Converting between datetime objects and ordinal values
Creating Periods
Basic Factory Methods
The Period
class provides various factory methods:
from time_stream import Period
# Create periods using specific methods
one_year = Period.of_years(1)
quarterly = Period.of_months(3)
one_month = Period.of_months(1)
one_day = Period.of_days(1)
one_hour = Period.of_hours(1)
fifteen_minutes = Period.of_minutes(15)
one_second = Period.of_seconds(1)
one_microsecond = Period.of_microseconds(1)
From ISO 8601 Duration Strings
You can create periods from ISO 8601 duration strings:
# Using ISO 8601 duration strings
one_year = Period.of_iso_duration("P1Y")
quarterly = Period.of_iso_duration("P3M")
one_month = Period.of_iso_duration("P1M")
one_day = Period.of_iso_duration("P1D")
one_hour = Period.of_iso_duration("PT1H")
fifteen_minutes = Period.of_iso_duration("PT15M")
one_second = Period.of_iso_duration("PT1S")
one_microsecond = Period.of_iso_duration("PT0.000001S")
From timedelta Objects
Convert Python timedelta objects to Periods (for intervals of time on the scale of days and below):
from datetime import timedelta
# Using timedelta objects
one_day = Period.of_timedelta(timedelta(days=1))
two_hours = Period.of_timedelta(timedelta(hours=2))
thirty_min = Period.of_timedelta(timedelta(minutes=30))
one_second = Period.of_timedelta(timedelta(seconds=1))
one_microsecond = Period.of_timedelta(timedelta(microseconds=1))
Periods with Offsets
Offsets allow you to create custom Periods that start at a point in time offset from the default. For example, a UK “Water year” starts on 9am October 1st. This would be defined with a 10 month and 9 hour offset to a 1 year period. Some more examples below:
# Water year (Starting on 9am Oct 1)
water_year = Period.of_years(1).with_month_offset(10).with_hour_offset(9)
# Water day starting at 9am
water_day = Period.of_days(1).with_hour_offset(9)
# Custom hour with 30-minute offset, e.g. for data with timestamps (00:30, 01:30, 02:30 ...)
hour_half = Period.of_hours(1).with_minute_offset(30)