hec

Module to provide native Python equivalent to HEC Java classes.

Quick links to Constants:

Quick links to Classes:

Time Instances and Periods
ClassExceptionDescription
HecTime HecTimeException Provides time instance-related calculations and manipulations. Mimics hec.helib.util.HecTime Java class
TimeSpan TimeSpanException Provides generic time- and calendar-based time span (period) information/operations
Interval IntervalException Provides time series recurrence interval information/operations
Duration DurationException Provides time series value duration information/operations
Numerical Quantities
ClassExceptionDescription
UnitQuantity UnitException Provides value (magnitude+unit) information/operations including unit conversions
Quality Holds quality assessments for numerical values
UsgsRounder Provides rounding operations for numerical values
Locations
ClassExceptionDescription
Location LocationException Holds information about locations
Parameters
ClassExceptionDescription
Parameter ParameterException Holds information about parameters for time series, ratings, etc...
ElevParameter ParameterException Holds information about elevation parameters (including vertical datum information)
ParameterType ParameterTypeException Holds information about the relation of parameters to durations
Time Series
ClassExceptionDescription
TimeSeries TimeSeriesException Holds time series information and provides operations for time series
TimeSeriesValue TimeSeriesException Holds information and provides operations for single time series values
Data Stores
ClassExceptionDescription
AbstractDataStore DataStoreException Abstract base class for all data store classes
CwmsDataStore DataStoreException Provides operations using CWMS databases for cataloging, retrieving, and storing data
DssDataStore DataStoreException Provides operations using HEC-DSS files for cataloging, retrieving, and storing data
Rating-related Classes
class AbstractDataStore(abc.ABC):

Abstract base class for data store classes

@abstractmethod
def catalog(self, data_type: Optional[str] = None, **kwargs: Any) -> List[str]:
@abstractmethod
def close(self) -> None:

Explicitly closes the data store, preventing further access.

The data store is implicitly closed upon deletion or exiting a context manager ('with' block)

@abstractmethod
def delete(self, identifier: str, **kwargs: Any) -> None:
end_time: Optional[HecTime]

The end time of the data store's time window (if any)

Operations:

Read/Write

@abstractmethod
def get_extents(self, identifier: str, **kwargs: Any) -> List[HecTime]:
native_data_store: Any
name: str

The name of the data store as provided in the constructor or open() method

Operations:

Read Only

office: Optional[str]

The office associated with the data store, if any

Operations:

Read/Write

@staticmethod
@abstractmethod
def open( name: Optional[str] = None, **kwargs: Any) -> AbstractDataStore:
is_open: bool

Whether this data store is open for cataloging and reading.

A data store is open from its construction or call to open() until a call to close() or deletiion

Operations:

Read Only

is_read_only: bool

Whether this data store is open for storing and deleting. Meaningless if is_open is False

Operations:

Read/Write

@abstractmethod
def retrieve(self, identifier: str, **kwargs: Any) -> Any:
start_time: Optional[HecTime]

The start time of the data store's time window (if any)

Operations:

Read/Write

@abstractmethod
def store(self, obj: object, **kwargs: Any) -> None:
time_window: Tuple[Optional[HecTime], Optional[HecTime]]

The data store's time window (if any)

  • Getting: same as (ds.start_time, ds.end_time)
  • Setting: same as ds.start_time, ds.end_time = tw
Operations:

Read/Write

time_zone: str

The time zone associated with the data store

When setting the time zone, any time window values are labeled with the specified time zone and not converted to the time zone

Operations:

Read/Write

trim: bool

Whether the datastore will trim missing values from the edges of retrieved regular time series

Operations:

Read/Write

units: str

The unit system ('EN' or 'SI') associated with the data store

Operations:

Read/Write

vertical_datum: Optional[str]

The vertical datum ('NGVD29', 'NAVD88', 'OTHER') associated with the data store

Returns:

Optional[str]: _description_

class Combine(enum.Enum):

Enumeration for combining selection states (current, new)

  • NOOP: Result is current selection state for all items
  • REPLACE: Result is new selection state for all items
  • AND: Result is current selection ANDed with new selection state
  • OR: Result is current selection ORed with new selection state
  • XOR: Result is current selection XORed with new selection state
NOOP = <Combine.NOOP: 0>
REPLACE = <Combine.REPLACE: 1>
AND = <Combine.AND: 2>
OR = <Combine.OR: 3>
XOR = <Combine.XOR: 4>
class CwmsDataStore(hec.AbstractDataStore):

Class to facilitate cataloging, storing, retrieving, and deleting data in CWMS databases.

Requires installation of the cwms-python >= '0.8.2'.

CwmsDataStore(**kwargs: Any)

Creates and returns a new CwmsDataStore object.

Equivalent of calling CwmsDataStore.open(name, **kwargs)

Arguments:
  • api_key (Optional[str], must be passed by name): The API key for this data store. Must be specified to write to or delete from this data store. Defaults to None. If None:
    • The value of environment variable "cda_api_key" is used, if it exists.
  • description (Optional[str], must be passed by name): The description assocaited with the data store. Defaults to None
  • end_time (Optional[Any], must be passed by name): Specifies the end time of the data store's time window. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to None
  • name (Optional[str], must be passed by name): The API root (base URL). Defaults to None. If None:
    • The value of environment variable "cda_api_root" is used, if it exists.
    • If the environment variable "cda_api_root" is not set, the default, the default value used in cwms.api.init_session(api_root=None) is used.
  • office (Optional[str], must be passed by name): The default CWMS office for the data store. If None or not specified, each access method will have to have an office specified.
  • read_only (Optional[bool], must be passed by name): Specifies whether to open the data store in read-only mode. Defaults to True
  • start_time (Optional[Any], must be passed by name): Specifies the start time of the data store's time window. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to None
  • store_rule (Optional[str], must be passed by name): Specifies the default behavior to use when storing data. If specified, it must be one of the following (case insensitive). Defaults to 'REPLACE_ALL'.
    • 'DELETE_INSERT' - delete all existing data in the incoming time window, then store the incoming data
    • 'DO_NOT_REPLACE' - store only non-existing data
    • 'REPLACE_ALL' - store existing and non-existing data
    • 'REPLACE_MISSING_VALUES_ONLY' - store incoming data only where existing data is missing
    • 'REPLACE_WITH_NON_MISSING' - store only non-missing incoming data
  • time_zone (Optional[str], must be passed by name): The default time zone for the data store. Defaults to the local time zone.
  • trim (Optional[bool], must be passed by name): Specifies the data store's default setting to trim missing values from the beginning and end of any regular time series data set retrieved. Defaults to True.
  • units: (Optional[str], must be passed by name): "EN" or "SI", specifying English or metric unit system as the default unit system for the data store. Defaults to "EN"
  • vertical_datum: (Optional[str], must be passed by name): "NGVD29", "NAVD88", or "NATIVE", specifying the data store's default vertical datum for retrieving elevation data. Defaults to "NATIVE"
def catalog(self, data_type: Optional[str] = None, **kwargs: Any) -> List[str]:

Retrieves CWMS Identifiers for the specified data type, optionally with extents for specific data types.

Arguments:
  • data_type (str): Must be one of the following (case insensitive):
    • 'LOCATION'
    • 'RATING'
    • 'RATING_SPECIFICATION'
    • 'RATING_TEMPLATE'
    • 'TIMESERIES'
  • pattern (Optional[str], must be passed by name): An extended wildcard pattern to use for matching Identifiers. regex takes precedence if both are specified. Defaults to None.

    Pattern Examples
    patternmatches
    abcthe literal string "abc"
    ab{2,3}c{2}1 "a" followed by 2 or 3 "b" followed by 2 "c"
    a*b?c1 "a" followed by zero or more characters followed by "b" followed by 1 character followed by 1 "c"
    [abc]1 "a" or "b" or "c"
    ^[abc]$beginning of string followed by 1 "a" or "b" or "c" followed by end of string
    [!abc]1 character other than "a" or "b" or "c"
    [_a-z0-9]*zero or more of characters "_" or "a" through "z" or "0" through "9"
    [!a-z0-9]{1,5}1..5 characters other than "a" through "z" or "0" through "9"
    (abc|def)either "abc" or "def"
  • regex (Optional[str], must be passed by name): Regular expression to use for matching Identifiers. Takes precedence over pattern if both are specified. Defaults to None.

  • bounding_office (Optional[str]), must be passed by name, LOCATION and TIMESERIES only): Specifies cataloging only Identifiers that are physically located within the boundaries of the specified office. Can be a wildcard pattern. Matching is affected by case_sensitive.
  • case_sensitive (Optional[bool], must be passed by name): Specifies whether and pattern or regular expression matching is case-sensitive.
  • category (Optional[str], must be passed by name, LOCATION only): Specifies cataloging only locations in a location group belonging to the specified catgory(ies). Can be a wildcard pattern. Matching is affected by case_sensitive. Note that specifying category or group, or including "aliases" in fields will slow down the catalog operation.
  • fields (Optional[str]), must be passed by name): A comma-separated list of fields to include in the catalog. Valid fields for data_type are listed below. The catalog will include the fields in the order specified. Defaults to identifier.
    • TIMESERIES:
      • identifier: The time series identifier
      • office: The CWMS office for the time series
      • name: Same as identifier
      • time-zone: The time zone of the location of the time seroies
      • interval: The interval of the time series
      • offset: The offset into each interval of regular time series (in minutes), or if interval is irregular
      • earliest-time: The earliest time in the database for this time series, or if no data
      • latest-time: The latest time in the database for this time series of if no data
      • last-update: The most recent time this time series has been updated, or of no data
    • RATING:
      • identifier: The rating specification
      • office: The CWMS office for the rating
      • name: Same as identifier
      • location: The location identifier
      • template: The rating template identifier
      • specification-version: The specification version
      • description: The description for the rating specification
      • lookup-methods: A comma-delimited string of effective date lookup methods (order = within-time-range, before-time-range, after-time-range)
      • specification-active: Whether the specification is active
      • auto-flags: True or False values for auto-update, auto-activate and auto-migrate-extensions, respectively
      • rounding-specs: A delimited string of rounding specifications for each indepedent and dependent parameter. Independent parameter roundings are comma-delimited; the dependent parameter rounding is semicolon-delimited.
      • effective-date: The effective date of the rating
      • create-date: The creation date date of the rating
      • units: The native units of the rating. Independent parameter units are comma-delimited; the dependent parameter unit is semicolon-delimited.
      • active: Whether the rating is active
      • type: The rating type
    • RATING_SPECIFICATION:
      • identifier: The rating specification
      • office: The CWMS office for the rating specification
      • name: Same as identifier
      • location: The location identifier
      • template: The rating template identifier
      • version: The specification version
      • description: The description for the rating specification
      • lookup-methods: A comma-delimited string of effective date lookup methods (order = within-time-range, before-time-range, after-time-range)
      • active: Whether the specification is active
      • auto-flags: True or False values for auto-update, auto-activate and auto-migrate-extensions, respectively
      • rounding-specs: A delimited string of rounding specifications for each indepedent and dependent parameter. Independent parameter roundings are comma-delimited; the dependent parameter rounding is semicolon-delimited.
      • effective-date: A comma-delimited string of effective date/times for ratings with this specification
    • RATING_TEMPLATE:
      • identifier: The rating template identifier
      • office: The CWMS office for the rating template
      • name: Same as identifier
      • independent-parameters: A comma-delimited string of independent parameter names
      • dependent-parameter: The dependent parameter name
      • version The template version
      • lookup-methods: A semicolon-delimited string of comma-delimited lookup methods for each independent parameter (order = in-range, below-range, above-range)
      • rating-ids: A list of rating ids that use the template. The rating ids are specified as the string representation of a list (i.e., an actual list can be obtained by passing this field to eval())
    • LOCATION:
      • identifier: The location identifier
      • office: The CWMS office for the location
      • name: Same as identifier
      • nearest-city: The name of the city or town closest to the location
      • public-name: The public name of the location
      • long-name: The long name of the location
      • kind: The kind of location - constrained to:
        • SITE
        • EMBANKMENT
        • OVERFLOW
        • TURBINE
        • STREAM
        • PROJECT
        • STREAMGAGE
        • BASIN
        • OUTLET
        • LOCK
        • GATE
      • time-zone: The time zone of the location
      • latitude: The latitude of the location
      • longitude: The latitude of the location
      • published-latitude: The published latitude of the location
      • published-longitude: The published longitude of the location
      • horizontal-datum: The horizontal datum associated with the latitude and longitude
      • elevation: The elevation of the location
      • unit: The unit of the elevation
      • vertical-datum: The vertical datum of the elevation
      • nation: The nation containing the location
      • state: The state/province containing the location
      • county: The county containing the location
      • bounding-office: The CWMS office whose boundary includes the location
      • map-label: The map label of the location
      • active: Whether the location is active
      • aliases: The aliases associated with the location. Note that including this slows down the catalog operation. The aliases are specified as the string representation of a dictionary (i.e., an actual dictionary can be obtained by passing this field to eval()). The dictionary keys are the location categories and groups for each alias, and the values are the aliases. The keys are of the form {category}-{group} (e.g., "Angency Aliases-NWS Handbook 5 ID")
      • description: The description of the location
      • type: The unconstrained type of the location (cf kind)
  • group (Optional[str], must be passed by name, LOCATION only): Specifies cataloging only locations in the specivied location group(s). Can be a wildcard pattern. Matching is affected by case_sensitive. Note that specifying category or group, or including "aliases" in fields will slow down the catalog operation.
  • header (Optional[bool], must be passed by name): Specifies whether to include a header line in the catalog that identifies the fields
  • kind (Optional[str], must be passed by name, LOCATION only): Specifies cataloging only locations of the specified location kind. Can be a wildcard pattern. Matching is affected by case_sensitive.
  • limit (Optional[int], must be passed by name, LOCATION and TIMESERIES only): The maximum number of Identifiers to return. If None, no limit is imposed. Defaults to None.
  • office (Optional[str], must be passed by name): The CWMS office to generate the catalog for. Defaults to None, which uses the data store's default office.
  • units (Optional[str], must be passed by name, LOCATION and TIMESERIES only): The unit system ("EN" or "SI") to return the elevation values in. Defaults to None.
  • vertical_datum (Optional[str], must be passed by name, LOCATION and TIMESERIES only): The vertical datum ("NGVD29", "NAVD88", or "LOCAL") to return the elevation values in. Defaults to None (Native datum).
Raises:
  • DataStoreException: if the data store is not open or an invalid data_type is specified
Returns:

List[str]: The CWMS Identifiers that match the specified parameters, up to the specified limit, if any

def close(self) -> None:

Explicitly closes the data store, preventing further access.

The data store is implicitly closed upon deletion or exiting a context manager ('with' block)

def delete(self, identifier: str, **kwargs: Any) -> None:

Deletes a data set from the data store.

Currently only time series data may be deleted.

Arguments:
  • identifier (str): The name of the data set to delete. Must be a valid one of the following:
    • time series identifier: start and end times specify the time window of time series values to delete, inclusive
  • delete_action (Optional[str], must be passed by name): Defaults to None. If specified, any time window is ignored and it must be one of (case insensitive):
    • 'DELETE_ALL': delete all data and the identifier for the object
    • 'DELETE_DATA': delete all data for the identifier but does not delete the identifier
    • 'DELETE_KEY': delete only the object identifier - will fail if any data is associated with the identifier
  • end_time (Optional[Any], must be passed by name): Specifies the end of the time window to delete data. Ignored if delete_action is specified. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to the end of the data store's time window.
  • office (Optional[str], must be passed by name): The CWMS office to delete data for. Defaults to None, which uses the data store's default office.
  • start_time (Optional[Any], must be passed by name): Specifies the start of the time window to delete data. Ignored if delete_action is specified. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to the start of the data store's time window.
  • version_time (Optional[Any], must be passed by name): Specifies the version date/time of the data to delete (time series types only). Must be an HecTime object or a valid input to the HecTime constructor. Defaults to the None, meaning non-versioned data.
def get_extents(self, identifier: str, **kwargs: Any) -> List[HecTime]:

Retrieves the data extents for the specified identifier

Arguments:
  • identifier (str): The identifier to retrieve the extents for
Returns:

List[HecTime]: The earliest time, latest time, and latest update time

def get_vertical_datum_info(self, identifier: str, **kwargs: Any) -> Optional[str]:

Retrieves the vertical datum information for a CWMS location

Arguments:
  • identifier (str): The location identifier
  • office (Optional[str]): The CWMS office for the location. Defaults to the data store's default office.
  • format (Optional[str]): The output format for the information. Must be one of 'JSON' or 'XML' (case insensitive). Defaults to 'JSON'
Returns:

Optional[str]: The vertical datum information in the specified format

is_open: bool

Whether this data store is open for cataloging and reading.

A data store is open from its construction or call to open() until a call to close() or deletiion

Operations:

Read Only

native_data_store: Any

The cwms module imported by this data store

Operations:

Read-Only

@staticmethod
def open(name: Optional[str] = None, **kwargs: Any) -> CwmsDataStore:

Creates and returns a new CwmsDataStore object.

Equivalent of calling CwmsDataStore(**kwargs) with name in kwargs

Arguments:
  • name (Optional[str]): The API root (base URL). Defaults to None. If None:
    • The value of environment variable "cda_api_root" is used, if it exists.
    • If the environment variable "cda_api_root" is not set, the default, the default value used in cwms.api.init_session() is used.
  • api_key (Optional[str], must be passed by name): The API key for this data store. Must be specified to write to or delete from this data store. Defaults to None. If None:
    • The value of environment variable "cda_api_key" is used, if it exists.
  • description (Optional[str], must be passed by name): The description assocaited with the data store. Defaults to None
  • end_time (Optional[Any], must be passed by name): Specifies the end time of the data store's time window. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to None
  • office (Optional[str], must be passed by name): The default CWMS office for the data store. If None or not specified, each access method will have to have an office specified.
  • read_only (Optional[bool], must be passed by name): Specifies whether to open the data store in read-only mode. Defaults to True
  • start_time (Optional[Any], must be passed by name): Specifies the start time of the data store's time window. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to None
  • store_rule (Optional[str], must be passed by name): Specifies the default behavior to use when storing data. If specified, it must be one of the following (case insensitive). Defaults to 'REPLACE_ALL'.
    • 'DELETE_INSERT' - delete all existing data in the incoming time window, then store the incoming data
    • 'DO_NOT_REPLACE' - store only non-existing data
    • 'REPLACE_ALL' - store existing and non-existing data
    • 'REPLACE_MISSING_VALUES_ONLY' - store incoming data only where existing data is missing
    • 'REPLACE_WITH_NON_MISSING' - store only non-missing incoming data
  • time_zone (Optional[str], must be passed by name): The default time zone for the data store. Defaults to the local time zone.
  • trim (Optional[bool], must be passed by name): Specifies the data store's default setting to trim missing values from the beginning and end of any regular time series data set retrieved. Defaults to True.
  • units (Optional[str], must be passed by name): "EN" or "SI", specifying English or metric unit system as the default unit system for the data store. Defaults to "EN"
  • vertical_datum (Optional[str], must be passed by name): "NGVD29", "NAVD88", or "NATIVE", specifying the data store's default vertical datum for retrieving elevation data. Defaults to "NATIVE"
def retrieve(self, identifier: str, **kwargs: Any) -> Any:

Retrieves a data set from the CWMS database.

Currently only Location, AbstractRatingSet TimeSeries objects may be retrieved.

To retrieve all data for a TimeSeries, specifiy start_time=None and end_time=None

Arguments:
  • Positional Arguments:
    • identifier (str): The name of the data set to retrieve. Must be a valid identifier for one of the retrievable data set types.
  • Keyword Arguments (Optional, must be passed by name):
    • All Identifiers:
      • office (str): The CWMS office to retrieve data for. Defaults to None, which uses the data store's default office.
    • Location Identifiers:
      • units (str): "EN" or "SI", specifying to retrieve data in English or metric units. Defaults to None, which uses the default unit system for the data store
      • vertical_datum (str): "NGVD29", "NAVD88", or "NATIVE", specifying the vertical datum to retrieve elevation data for. Defaults to None, which uses the data store's default vertical datum
    • Rating Set Identifiers:
      • effective_time (datetime): Retrieves a LocalRatingSet object with only one rating (at the specified effective_time). Causes the method argument to be ignored, with "EAGER" retrieval implied. Used by the library to populate the rating points of individual TableRating objects that were previously retrieved with the "LAZY" method.
      • method (str): The method used to retrieve the rating set from the database. Restricted to "EAGER", "LAZY", and "REFERENCE". Defaults to "LAZY".
        • If "REFERENCE", a ReferenceRatingSet is retrieved, where all values are sent to the database to be rated.
        • If "EAGER", a LocalRatingSet is retrieved, where all ratings are performed in python code. Rating points for all included TableRating objects are retrieved when the rating set is retrieved.
        • If "LAZY", a LocalRatingSet is retrieved, where all ratings are performed in python code. Rating points for all included TableRating objects are not retrieved until when the individual TableRating objects are first used.
    • Time Series Identifiers:
      • start_time (Any): Specifies the start of the time window to retrieve data. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to the start of the data store's time window. If None or not specified and the data store's time window doesn't have a start time, the current time minus 24 hours is used
      • end_time (Any): Specifies the end of the time window to retrieve data. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to the end of the data store's time window. If None or not specified and the data store's time window doesn't have an end time, the current time is used
      • trim (bool): Specifies whether to trim missing values from the beginning and end of any regular time series data set retrieved. Defaults to the data store's trim setting.
      • units (str): "EN" or "SI", specifying to retrieve data in English or metric units. Defaults to None, which uses the default unit system for the data store
      • version_time (Any)): Specifies the version date/time of the data to retrieve (time series types only). Must be an HecTime object or a valid input to the HecTime constructor. Defaults to the None, which uses the data store's default vertical datum.
      • vertical_datum (str): "NGVD29", "NAVD88", or "NATIVE", specifying the vertical datum to retrieve elevation data for. Defaults to None, which uses the data store's default vertical datum
Returns:

Any: The Location, AbstractRatingSet TimeSeries object

def store(self, obj: object, **kwargs: Any) -> None:

Stores a data set to the data store.

Currently only locations and time series data may be stored.

Arguments:
  • obj (object): The data set to store.
    • For locations, must be a Location object or the name of the location
  • Location Arguments:

    • name (Optional[str], must be passed by name): The location's name, Defaults to the Location object's name
    • office (Optional[str], must be passed by name): The location's office. Defaults to the Location object's office
    • kind (str, must be passed by name): The location's kind. Must be on of:
      • SITE
      • EMBANKMENT
      • OVERFLOW
      • TURBINE
      • STREAM
      • PROJECT
      • STREAMGAGE
      • BASIN
      • OUTLET
      • LOCK
      • GATE
    • active (Optional[bool], must be passed by name): Whether the location is active in the datbase. Defaults to True
    • latitude (Optional[float], must be passed by name): The location's latitude. Defaults to the Location object's latitude.
    • longitude (Optional[float], must be passed by name): The location's longitude. Defaults to the Location object's longitude
    • horizontal_datum (Optional[str], must be passed by name): The location's horizontal datum
    • elevation (Optional[float], must be passed by name): The location's elevation. Defaults to the Location object's elevation
    • elevation_unit (Optional[str], must be passed by name): The unit of the location's elevation. Defaults to the Location object's elevation unit
    • vertical_datum (Optional[str], must be passed by name): The location's vertical datum. Defaults to the location's vertical datum
    • nation (Optional[str], must be passed by name): The location's nation. Defaults to "US"
    • state (Optional[str], must be passed by name): The location's state. Defaults to None
    • county (Optional[str], must be passed by name): The locations's county. Defaults to None
    • bounding_office (Optional[str], must be passed by name): The CWMS office whose boundar includes the location. Defaults to None
    • nearest_city (Optional[str], must be passed by name): The city nearest the location. Defaults to None
    • time_zone (Optional[str], must be passed by name): The location's time zone. Defaults to the location's time zone
    • public_name (Optional[str], must be passed by name): The location's public name. Defaults to None
    • long_name (Optional[str], must be passed by name): The location's long name. Defaults to None
    • description (Optional[str], must be passed by name): The location's description. Defaults to None
    • map_label (Optional[str], must be passed by name): The location's map label. Defaults to None
    • published_latitude (Optional[float], must be passed by name): The published latitude of the location. Defaults to None
    • published_longitude (Optional[float], must be passed by name): The published longitude of the location. Defaults to None
    • type (Optional[str], must be passed by name): An unconstrained type for the location. Defaults to None
       
    The following items are required to be specified either in the Location object or arguments:
    • name
    • office
    • kind
    • latitude
    • longitude
    • horizontal_datum
    • time_zone

  • TimeSeries Arguments:
    • as_lrts (Optional[bool], must be passed by name): Specifies whether to store the time series as LRTS is its interval starts with "~". Defaults to whether the time series is a local regular time series
    • override_protecteion (Optional[bool], must be passed by name): Specifies whether to store non-protected values over existing protected values. (Protected values always overwrite existing values and non-protected existing values are alway overwritten) Defaults to False
    • store_rule (Optional[str], must be passed by name): Specifies the default behavior to use when storing data. If specified, it must be one of the following (case insensitive). Defaults to 'REPLACE_ALL'.
      • 'DELETE_INSERT' - delete all existing data in the incoming time window, then store the incoming data
      • 'DO_NOT_REPLACE' - store only non-existing data
      • 'REPLACE_ALL' - store existing and non-existing data
      • 'REPLACE_MISSING_VALUES_ONLY' - store incoming data only where existing data is missing
      • 'REPLACE_WITH_NON_MISSING' - store only non-missing incoming data
class DataStoreException(builtins.Exception):

Base class for all data store exceptions

class DeleteAction(enum.Enum):

An enumeration.

DELETE_ALL = <DeleteAction.DELETE_ALL: 1>
DELETE_DATA = <DeleteAction.DELETE_DATA: 2>
DELETE_KEY = <DeleteAction.DELETE_KEY: 3>
class DssDataStore(hec.AbstractDataStore):

Class to facilitate cataloging, storing, retrieving, and deleting data in HEC-DSS files.

Requires installation of the 'hecdss' package >= '0.1.28'.

Note on using DssDataStore objects with rating objectsDssDataStore objects can be used to store and retrieve LocalRatingSet objects. Since these objects are not identifiable with a single pathname, rating specification identifiers (which are mapped to multiple pathnames) are used to retrieve LocalRatingSet objects from the data store. The portions of rating sets (i.e., rating templates, rating specifications, and individual ratings) may be cataloged with the appropiate identifiers mathched by the pattern or regex keyword arguments to the catalog() method: For cataloging purposes, the data_type parameter must be specified (i.e., "RATING_TEMPLATE", "RATING_SPECIFICATION" or "RATING"). The catalog() method normally returns identifiers for these data types, but specifying pathnames=True causes pathnames to be returned instead, as shown in the command-line session below. All rating related pathnames have D pathname parts that start with "Rating-". The mapping of the CWMS-style identifiers onto HEC-DSS pathnames is:

Object Type A Part B Part C Part D Part E Part F Part Record Body
Rating Template Office ID Parameters ID "Rating‑Template" Template Version Rating Template XML
Rating Specification Office ID Location ID Parameters ID "Rating‑Specification" Template Version Specification Version Rating Specification XML
Rating Office ID Location ID Parameters ID "Rating‑Body‑Effective‑Time" Template Version Specification Version Rating XML minus any TableRating points (for lazy loading)
Table Rating Points Office ID Location ID Parameters ID "Rating‑Points‑Effective‑Time" Template Version Specification Version Rating XML including any TableRating points (for populating after lazy loading)
For example, in the image below, LocalRatingSet with the following rating specification identifiers have been stored to an empty HEC-DSS file. Both rating sets were for office SWT.
  • COUN.Count-Conduit_Gates,Opening-Conduit_Gates,Elev;Flow-Conduit_Gates.Standard.Production/
  • KEYS.Elev;Stor.Linear.Production/

The following command line session demonstrates cataloging the file and retrieving one of the rating sets:

>>> from hec import DssDataStore
>>> dss = DssDataStore.open(r"U:\Devl\git\hec-python-library\test\resources\rating\local_rating_set.dss")
16:50:45.507      -----DSS---zopen   Existing file opened,  File: U:\Devl\git\hec-python-library\test\resources\rating\local_rating_set.dss
16:50:45.507                         Handle 3;  Process: 18724;  DSS Versions - Software: 7-IU, File:  7-IU
16:50:45.508                         Single-user advisory access mode
>>>
>>> for item in dss.catalog("RATING_TEMPLATE"): print(item)
...
Count-Conduit_Gates,Opening-Conduit_Gates,Elev;Flow-Conduit_Gates.Standard
Elev;Stor.Linear
>>>
>>> for item in dss.catalog("RATING_TEMPLATE", pathnames=True): print(item)
...
/SWT//Count-Conduit_Gates,Opening-Conduit_Gates,Elev;Flow-Conduit_Gates/Rating-Template/Standard//
/SWT//Elev;Stor/Rating-Template/Linear//
>>>
>>> for item in dss.catalog("RATING_SPECIFICATION"): print(item)
...
COUN.Count-Conduit_Gates,Opening-Conduit_Gates,Elev;Flow-Conduit_Gates.Standard.Production
KEYS.Elev;Stor.Linear.Production
>>>
>>> for item in dss.catalog("RATING_SPECIFICATION", pathnames=True): print(item)
...
/SWT/COUN/Count-Conduit_Gates,Opening-Conduit_Gates,Elev;Flow-Conduit_Gates/Rating-Specification/Standard/Production/
/SWT/KEYS/Elev;Stor/Rating-Specification/Linear/Production/
>>>
>>> for item in dss.catalog("RATING"): print(item)
...
COUN.Count-Conduit_Gates,Opening-Conduit_Gates,Elev;Flow-Conduit_Gates.Standard.Production
KEYS.Elev;Stor.Linear.Production
>>>
>>> for item in dss.catalog("RATING", pathnames=True): print(item)
...
/SWT/COUN/Count-Conduit_Gates,Opening-Conduit_Gates,Elev;Flow-Conduit_Gates/Rating-Body-2012-04-26T05:00:00Z/Standard/Production/
/SWT/COUN/Count-Conduit_Gates,Opening-Conduit_Gates,Elev;Flow-Conduit_Gates/Rating-Body-2012-04-27T05:00:00Z/Standard/Production/
/SWT/KEYS/Elev;Stor/Rating-Body-2009-01-14T06:00:00Z/Linear/Production/
/SWT/KEYS/Elev;Stor/Rating-Body-2011-10-19T05:00:00Z/Linear/Production/
/SWT/KEYS/Elev;Stor/Rating-Body-2020-08-01T05:00:00Z/Linear/Production/
>>>
>>> rs = dss.retrieve("KEYS.Elev;Stor.Linear.Production", office="SWT")
>>> print(type(rs))
<class 'hec.rating.local_rating_set.LocalRatingSet'>
>>>
>>> for effective_time in rs.ratings: print(effective_time.isoformat(), rs.ratings[effective_time])
...
2009-01-14T06:00:00+00:00 <hec.rating.table_rating.TableRating object at 0x0000019CBC556EB0>
2011-10-19T05:00:00+00:00 <hec.rating.table_rating.TableRating object at 0x0000019CBC59C220>
2020-08-01T05:00:00+00:00 <hec.rating.table_rating.TableRating object at 0x0000019CBC600880>
DssDataStore(**kwargs: Any)

Creates and returns a new DssDataStore object.

Equivalent of calling DssDataStore.open(name, **kwargs)

Arguments:
  • description (Optional[str], must be passed by name): The description assocaited with the data store. Defaults to None
  • end_time (Optional[Any], must be passed by name): Specifies the end time of the data store's time window. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to None
  • name (str, must be passed by name): The name of the HEC-DSS file to open.
  • read_only (Optional[bool], must be passed by name): Specifies whether to open the data store in read-only mode. Defaults to True
  • start_time (Optional[Any], must be passed by name): Specifies the start time of the data store's time window. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to None
  • store_rule (Optional[str], must be passed by name): Must be one of the following (case insensitive). Defaults to 'REPLACE_ALL'.
    • 'DELETE_INSERT'
    • 'DO_NOT_REPLACE'
    • 'REPLACE_ALL'
    • 'REPLACE_MISSING_VALUES_ONLY'
    • 'REPLACE_WITH_NON_MISSING'
  • trim (Optional[bool], must be passed by name): Specifies the data store's default setting to trim missing values from the beginning and end of any regular time series data set retrieved. Defaults to True.
def catalog(self, data_type: Optional[str] = None, **kwargs: Any) -> List[str]:

Retrieves pathnames that match specified conditions.

If data_type is "RATING", "RATING-SPECIFICATION", or "RATING-TEMPLATE", CWMS-style identifiers are returned instead of pathnames unless the pathnames parameter is specifed as True. (See Note on use with rating objects)

Arguments:
  • data_type (Optional[str]): The type of data to retrieve pathnames for. Defaults to None, which specifies all data types. If specified, must be one of (case insensitive):
    • 'ARRAY'
    • 'GRID'
    • 'LOCATION'
    • 'PAIRED_DATA'
    • 'RATING'
    • 'RATING_SPECIFICATION'
    • 'RATING_TEMPLATE'
    • 'TEXT'
    • 'TIMESERIES'
    • 'TIMESERIES_PROFILE'
    • 'TIN'
  • pattern (Optional[str], must be passed by name): Wildcard pattern (using * and ?) to use for matching pathnames. regex takes precedence if both are specified. Defaults to None (all pathnames are returned).

    If data_type is "RATING", "RATING-SPECIFICATION", or "RATING-TEMPLATE", the pattern matches the CWMS-style identifiers instead of pathnames.

    Pattern Examples
    patternmatches
    abcthe literal string "abc"
    ab{2,3}c{2}1 "a" followed by 2 or 3 "b" followed by 2 "c"
    a*b?c1 "a" followed by zero or more characters followed by "b" followed by 1 character followed by 1 "c"
    [abc]1 "a" or "b" or "c"
    ^[abc]$beginning of string followed by 1 "a" or "b" or "c" followed by end of string
    [!abc]1 character other than "a" or "b" or "c"
    [_a-z0-9]*zero or more of characters "_" or "a" through "z" or "0" through "9"
    [!a-z0-9]{1,5}1..5 characters other than "a" through "z" or "0" through "9"
    (abc|def)either "abc" or "def"
  • regex (Optional[str], must be passed by name): Regular expression to use for matching pathnames. Takes precedence over pattern if both are specified. Defaults to None (all pathnames are retuned). If data_type is "RATING", "RATING-SPECIFICATION", or "RATING-TEMPLATE", the regex matches the CWMS-style identifiers instead of pathnames.

  • case_sensitive (Optional[bool], must be passed by name): Specifies whether pattern or regex matching is case-sensitive. Defaults to False.
  • condensed (Optional[bool], must be passed by name): Specifies whether to return a condensed catalog (D-part = time range for time series). Defaults to True
  • office (Optional[str], must be passed by name): Specifies the office if data_type is "RATING", "RATING-SPECIFICATION", or "RATING-TEMPLATE". Defaults to None (all offices are matched).
  • pathnames (Optional[bool]), must be passed by name: Specifies whether to return pathnames instead of identifiers if data_type is "RATING", "RATING-SPECIFICATION", or "RATING-TEMPLATE". Defaults to False.
Raises:
  • DataStoreException: if the data store is not open or an invalid data_type is specified
Returns:

List[str]: The pathnames that match the specified parameters

def close(self) -> None:

Explicitly closes the data store, preventing further access.

The data store is implicitly closed upon deletion or exiting a context manager ('with' block)

def delete(self, identifier: str, **kwargs: Any) -> None:

Deletes a data set from the data store.

Currently only time series data may be deleted. To delete all data for a time series, specifiy start_time=None and end_time=None

Arguments:
  • identifier (str): The name of the data set to delete:
    • TIMESERIES: A pathname in the dataset. The D part (block start date) is ignored.
  • end_time (Optional[Any], must be passed by name): Specifies the end of the time window to delete data. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to the end of the data store's time window. If None or not specified and the data store's time window doesn't have an end time, all data on or after the start time will be deleted.
  • start_time (Optional[Any], must be passed by name): Specifies the start of the time window to delete data. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to the start of the data store's time window. If None or not specified and the data store's time window doesn't have a start time, all data up to and on the end time will be deleted.
@staticmethod
def decode_ints(ints: list[int]) -> str:
@staticmethod
def encode_str(s: str) -> list[int]:
def get_extents(self, identifier: str, **kwargs: Any) -> List[HecTime]:

Retrieves the data extents for the specified identifier

Arguments:
  • identifier (str): The identifier to retrieve the extents for
Returns:

List[HecTime]: The earliest time and latest time for the identifier

is_open: bool

Whether this data store is open for cataloging and reading.

A data store is open from its construction or call to open() until a call to close() or deletiion

Operations:

Read Only

native_data_store: Any

The underlying HecDss object from the imported library used by this data store

Operations:

Read-Only

@staticmethod
def open(name: Optional[str] = None, **kwargs: Any) -> DssDataStore:

Creates and returns a new DssDataStore object.

Equivalent of calling DssDataStore(**kwargs) with name in kwargs

Arguments:
  • name (str): The name of the HEC-DSS file to open.
  • description (Optional[str], must be passed by name): The description assocaited with the data store. Defaults to None
  • end_time (Optional[Any], must be passed by name): Specifies the end time of the data store's time window. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to None
  • read_only (Optional[bool], must be passed by name): Specifies whether to open the data store in read-only mode. Defaults to True
  • start_time (Optional[Any], must be passed by name): Specifies the start time of the data store's time window. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to None
  • store_rule (Optional[str], must be passed by name): Must be one of the following (case insensitive). Defaults to 'REPLACE_ALL'.
    • 'DELETE_INSERT'
    • 'DO_NOT_REPLACE'
    • 'REPLACE_ALL'
    • 'REPLACE_MISSING_VALUES_ONLY'
    • 'REPLACE_WITH_NON_MISSING'
  • trim (Optional[bool], must be passed by name): Specifies the data store's default setting to trim missing values from the beginning and end of any regular time series data set retrieved. Defaults to True.
def retrieve(self, identifier: str, **kwargs: Any) -> Any:

Retrieves a data set from the data store.

Currently only LocalRatingSet, PairedData and TimeSeries objects can be retrieved. (See Note on use with rating objects)

To retrieve all data for a TimeSeries, specifiy start_time=None and end_time=None

Arguments:
  • Positional Arguments:
    • identifier (str): The name of the data set to retrieve:
      • LocalRatingSet: A valid rating specification identifier. NOTE: LocalRatingSet objects cannot be retrieved by pathname.
      • PairedData: A valid paired-data pathname
      • TimeSeries: A valid time series pathname. NOTE: Unlike the Java HEC-DSS library, the D part (block start date) is always ignored. Set the datastore time window or use start_time and end_time keyword arguments to retrieve data for a time window.
  • Keyword Arguments (Optional, must be passed by name):
    • LocalRatingSet Identifiers:
      • effective_time (datetime): Retrieves a LocalRatingSet object with only one rating (at the specified effective_time). Causes the method argument to be ignored, with "EAGER" retrieval implied. Used by the library to populate the rating points of individual TableRatingSet objects that were previously retrieved with the "LAZY" method.
      • method (str): The method used to retrieve the rating set from the HEC-DSS file. Restricted to "EAGER" and "LAZY".
        • If "EAGER", a LocalRatingSet is retrieved with rating points for all included TableRating objects are retrieved fully populated.
        • If "LAZY", a LocalRatingSet is retrieved omitting the rating points for all included TableRating objects until they are first needed.
    • PairedData Identifiers:
      • dep_rounding (UsgsRounder|str): Rounds all of the dependent parameter values using the specified rounder or rounding spec after retrieval from the HEC-DSS file.
      • ind_rounding (UsgsRounder|str): Rounds all of the independent parameter values using the specified rounder or rounding spec after retrieval from the HEC-DSS file.
      • rounding (UsgsRounder|str): Rounds all of the independent and dependent parameter values using the specified rounder or rounding spec after retrieval from the HEC-DSS file.
    • TimeSeries Identifiers:
      • end_time (Any): Specifies the end of the time window to retrieve data. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to the end of the data store's time window. If None or not specified and the data store's time window doesn't have an end time, all data on or after the start time will be retrieved.
      • start_time (Any): Specifies the start of the time window to retrieve data. Must be an HecTime object or a valid input to the HecTime constructor. Defaults to the start of the data store's time window. If None or not specified and the data store's time window doesn't have a start time, all data up to and on the end time will be retrieved.
      • trim (bool): Specifies whether to trim missing values from the beginning and end of any regular time series data set retrieved. Defaults to the data store's trim setting.

Returns (Any): The retrieved LocalRatingSet, PairedData or TimeSeries object.

@staticmethod
def set_message_level(level: int = 4) -> None:

Sets the HEC-DSS message level for all DssDataStore objects

Arguments:
  • level (int, optional): Defaults to 4
    • 0: No output
    • 1: Critcal output only
    • 2: Terse (includes file open and close)
    • 4: General (includes read and write)
    • 5: User Diagnostic
    • 11: Internal Diagnostic
    • 13: Internal Debug
def store(self, obj: object, **kwargs: Any) -> None:

Stores a data set to the data store.

Currently only time series and rating sets may be stored.

Arguments:
  • obj (object): The data set to store
class Duration(hec.TimeSpan):

Class to hold information about the durations represented by time series values.

Durations are a restriction of the TimeSpan base class that also hold extra information.

  • Restriction: At most one of years, months, days, hours, and minutes can be non-zero, and seconds must be zero.
  • Extension:
    • Each duration has a name
    • Each duration is a Beginning of Period (BOP) or End of Period (EOP) duration. Normally values represent the state at the end of duration (e.g, the elevation or flow at the end of an hour or day). EOP Duration objects are returned unless otherwise specified.

Durations should not need to be created by the user, as durations for all CWMS intervals are created during module initialization.

Duration(interval: Union[Interval, str], bop: bool = False)

Initializer used by module

is_bop: bool

Whether this object is a Beginning of Period Duration

Operations:

Read-only

is_eop: bool

Whether this object is an End of Period Duration

Operations:

Read-only

@staticmethod
def for_interval( interval: Union[Interval, str, int], bop: bool = False) -> Duration:

Returns a Duration object for a specified interval

Arguments:
  • interval (Union[Interval, str, int]): A standard CWMS Interval object, or the name or (actual or characteristic) minutes of a standard CWMS interval
  • bop (bool, optional): Specifies whether to return a Beginning of Period Duration object. Defaults to False.
Raises:
  • TypeError: If the first argument is not an Interval, string, or integer
  • DurationException: If the first argument a non-standard name or minutes or no such Duration object exists
Returns:

Duration: The Duration object matching the specified interval and bop setting.

minutes: int

The minutes (actual or characteristic) of this object

Operations:

Read-only

name: str

The name of this object

Operations:

Read-only

class DurationException(hec.TimeSpanException):

Exception specific to Duration operations

class ElevParameter(hec.Parameter):

Holds info (name and vertical datum information) for an elevation parameter

ElevParameter( name: str, vertical_datum_info: Union[str, dict[str, Any], NoneType] = None)

Initializes the ElevParameter object

Arguments:
  • name (str): The full parameter name
  • vertical_datum_info (Union[str, dict[str, Any]]): The vertical datum info as an xml string or dictionary
Raises:
def clone(self) -> ElevParameter:

Returns a copy of this object

Returns:

ElevParameter: The copy

current_datum: Optional[str]

The current datum of this object

Operations:

Read/Write

elevation: Optional[UnitQuantity]

The elevation of this object in the current datum and unit

Operations:

Read Only

def get_offset_to(self, target_datum: str) -> Optional[UnitQuantity]:

Returns the offset from the current vertical datum to the specified target datum in the current unit.

Arguments:
  • target_datum (str): The target datum
Raises:
Returns:

Optional[UnitQuantity]: The offset from the current datum to the target datum or None if the current and target datums are the same.

def ito( self, unit_or_system_or_datum: Union[str, pint.registry.Unit]) -> ElevParameter:

Converts this object to the specified unit or vertical datum and returns it.

Identical to calling .to(unit_or_system_or_datum, in_place=True

Arguments:
  • unit_or_system_or_datum (Union[str, Unit]): The unit, unit_system, or vertical datum to convert to. If unit system ("EN" or "SI"), the default Elev unit for that system is used.
Returns:

ElevParameter: The converted object, whether this object of a copy of it

native_datum: Optional[str]

The native datum of this object

Operations:

Read Only

navd88_offset: Optional[UnitQuantity]

The offset from the native datum of this object to NGVD-29, in the current unit, or None if
* the native vertical datum is NGVD-29 * the native vertical datum is not NGVD-29, but the object does not have such an offset

Operations:

Read Only

navd88_offset_is_estimate: Optional[bool]

Whether the offset from the native vertical datum to NGVD-29 is an estimate (e.g, VERTCON) or None if the native vertical datum is NGVD-29 or the object does not have such and offset

Operations:

Read Only

ngvd29_offset: Optional[UnitQuantity]

The offset from the native datum of this object to NGVD-29, in the current unit, or None if
* the native vertical datum is NGVD-29 * the native vertical datum is not NGVD-29, but the object does not have such an offset

Operations:

Read Only

ngvd29_offset_is_estimate: Optional[bool]

Whether the offset from the native vertical datum to NGVD-29 is an estimate (e.g, VERTCON) or None if the native vertical datum is NGVD-29 or the object does not have such and offset

Operations:

Read Only

def to( self, unit_or_system_or_datum: Union[str, pint.registry.Unit], in_place: bool = False) -> ElevParameter:

Converts either this object or a copy of it to the specified unit or vertical datum and returns it

Arguments:
  • unit_or_system_or_datum (Union[str, Unit]): The unit, unit_system, or vertical datum to convert to. If unit system ("EN" or "SI"), the default Elev unit for that system is used.
  • in_place (bool, optional): If True, this object is converted and returned, otherwise a copy is converted and returned. Defaults to False.
Returns:

ElevParameter: The converted object, whether this object of a copy of it

unit: pint.registry.Unit

The unit of this object

Operations:

Read Only

unit_name: str

The unit name of this object

Operations:

Read Only

vertical_datum_info: Optional[hec.parameter.ElevParameter._VerticalDatumInfo]

The VerticalDatumInfo object of this parameter

Operations:

Read Only

vertical_datum_info_dict: Optional[dict[str, Any]]

The VerticalDatumInfo object of this parameter as a dictionary

Operations:

Read Only

vertical_datum_info_xml: Optional[str]

The VerticalDatumInfo object of this parameter as an xml string

Operations:

Read Only

class ElevParameter.VerticalDatumException(hec.ParameterException):

Exception specific to vertical datum operations

@total_ordering
class HecTime:

Class to facilitate moving Jython scripts that use Java class hec.heclib.util.HecTime to Python

Implementation:

Compatibility with Java HecTime

This class replicates the capabilities of the Java hec.heclib.util.HecTime class, and uses the same method names except the camel case names of the Java class have been renamed to snake case to match Python naming standards as shown in the following examples:

Java Method NamePython Method Name
adjustToIntervalOffset()adjust_to_interval_offset()
computeNumberIntervals()compute_number_intervals()

Granularity

Like Java HecTime, HecTime objects can be instaniated with different time granularities, with each granule specifying a second, minute, hour, or day. Specifically:

GranularityInteger RangeEach Granule SpecifiesDate Range
SECOND_GRANULARITY
= 10
-2147483648
+2147483647
Seconds after
01Jan1970, 00:00
+1901-12-13T20:45:52
+2030-01-19T03:14:17
MINUTE_GRANULARITY
= 11
-2147483648
+2147483647
Minutes after
31Dec1899, 00:00
-2184-12-06T21:52
+5983-01-23T02:07
HOUR_GRANULARITY
= 12
-2147483648
+2147483647
Hours after
31Dec1899, 00:00
-243084-03-22T16
+246883-10-08T07
DAY_GRANULARITY
= 13
-2147483645
+2146789687
Days after
31Dec1899
-5877711-06-22
+5879610-07-10

The default granularity is MINUTE_GRANULARITY, but this may be overridden when calling HecTime().

Chainable methods

Since, unlike Java, Python allows code to ignore the return value from functions and methods, many HecTime methods with a void return type in Java now return a modified HecTime object. This allows the chaining of methods together for simplify code. For example:

t = HecTime()
t.set_current()
t.adjust_to_interval_offset(intvl, 0)
t.increment(1, intvl)

can now be coded as:

t = HecTime.now().adjust_to_interval_offset(intvl, 0).increment(1, intvl)

although the previous style is still supported.

Compatibility with datetime

This class is written to be trivially convertable to/from datetime objects and updatable via timedelta objects. Like datetime objects, HecTime objects are not time zone aware unless given time zone information. For HecTime objects the label_as_time_zone() method is used for this purpose. Also like datetime objects, using the astimezone() method causes the object to act as if it had been initialized with the local time zone.

Initialization from a datetime object is acccomplished via ht = HecTime(dt_obj). Retieval of a datetime object is accomplished via dt_obj = ht.datetime(). The HecTime.label_as_time_zone(tz) accomplishes the same thing as datetime.replace(tzinfo=tz), and the HecTime.astimezone(tz) accomplishes the same thing as datetime.astimezone(tz)

datetime methods, properties, and operators supported in HecTime objects are:

  • Methods
    • now() (static method)
    • astimezone(timezone)*
    • strftime(format)
    • strptime(date_time_str, format)
    • __str__() (used in print())
  • Properties
  • Operators
    • + and +=
    • - and -=
    • == and !=
    • < and <=
    • > and >=`

*The astimezone(timezone), method, like all HecTime methods that take time zone will accept:

  • ZoneInfo object
  • String (timezone name)
  • HecTime object (the object's time zone is used)
  • datetime object (the object's time zone is used)

Note: Compatibility with datetime as well as time zone support is only available on HecTime objects that are within the datetime object range of 01Jan0001, 00:00 through 31Dec9999, 23:59. Also, time zone support is not provided for HecTime objects of DAY_GRANULARITY.

Addition, subtraction, and comparison operators

Integers, HecTime objects, TimeSpan objects, Interval objects, Duration objects, timedelta objects, and specially formatted strings (see below) can be used on the right side of the + and += operators. The result is always another HecTime object. Allowing HecTime objects to be added to each other breaks the similarity with datetime, but is included to provide the functionality Java HecTime.

Integers, HecTime objects, datetime objects, TimeSpan objects, Interval objects, Duration objects, timedelta objects, and specially formatted strings (see below) can be used on the right side of the - or -= operators.

  • The result is an HecTime object when subtracting intgers, TimeSpan objects, Interval objects, Duration objects, timedelta objects and strings.
  • The result is a TimeSpan object when subtracting HecTime objects
  • The result is a timedelta object when subtracting datetime objects

If the HecTime object on the left side of any +, -, +=, or -= operator has a time zone attached and the right- side object is an Interval has the is_local_regular property of True, then addition and subtraction is performed with respect to the time zone of the HecTime object. For example if the HecTime object is at midnight in the US/Pacific time zone, then adding a local-regular interval of 2 hours will result in an HecTime object at 2 a.m. in the same time zone. The actual amount of time added with respect to UTC will be 1, 2, or 3 hours, depending on the day, month, and year.

Adding and subtracting integers adds or subracts the number of granules in the object so the change may be in seconds, minutes, hours, or days, depending on the object's granularity.

Strings of the format used for the offset portion of relative time strings in get_time_window() can be used in addition and subtraction operators. Examples

  • t - "1y" would return an HecTime object one year prior to the t object
  • t += "3m-2d+1h" would increment the t object forward 3 months, back 2 days and forward 1 hour.

This precludes using ISO 8601 duration strings that have minutes or seconds components. To use these, create a TimeSpan object from the string for the addend

HecTime objects can be compared with each other or with datetime objects using the standard operators (==, !=, <, <=, >, >=). Either type may be on either side of the operators.

Use of properties

Many methods are deprecated and will generate deprecation warnings when used. Most have been replaced by direct read/write or read-only properties.

The value(), year(), month(), day(), hour(), minute(), and second() methods are still supported but are accessed in a more pythonic way as read/write (value) or read-only (year, month, day, hour, minute, second) properties. There is no clean way to issue deprecation warning if these properties are accessed by their getter functions.

HecTime(*args: Any)

Initializes a newly-created HecTime object.

Arguments:

Raises:
  • HecTimeException: if invalid parameters are specified
def add( self, time: Union[int, HecTime, TimeSpan, datetime.timedelta, str]) -> HecTime:

Adds an number of granules or an HecTime to this object

Arguments:
  • other (Union[int, "HecTime", TimeSpan, timedelta, str]): item to add
Deprecated:

Use the += operator instead

Returns:

HecTime: The modified object

def add_days(self, days: int) -> HecTime:

Adds a number of days to the object

Arguments:
  • days (int): the number of days to add.
Returns:

HecTime: The modified object

def add_hours(self, hours: int) -> HecTime:

Adds a number of hours to the object

Arguments:
  • hours (int): the number of hours to add.
Returns:

HecTime: The modified object

def add_minutes(self, minutes: int) -> HecTime:

Adds a number of minutes to the object

Arguments:
  • minutes (int): the number of minutes to add.
Returns:

HecTime: The modified object

def add_seconds(self, seconds: int) -> HecTime:

Adds a number of seconds to the object

Arguments:
  • seconds (int): the number of seconds to add.
Returns:

HecTime: The modified object

def adjust_to_interval_offset( self, interval: Union[Interval, int], offset_minutes: int) -> HecTime:

Adjusts this object to be at the specified offset past the specified interval.

NOTE: Unlike zofset The resulting time may be at, before, or after the this object, but will always be in the interval that begins at or before this object.

To get the begninning of the interval that starts at or before this object, set offset_minutes to 0. To get the beginning of the next interval set offset_minutes be the same as interval_minutes.

Arguments:
  • interval (Union[Interval, int]): The interval. If an integer, must be the actual or charactersitic minutes of a standard Interval
  • offset_minutes (int): The offset into the interval in minutes (0..interval)
Returns:

The adjusted object

Raises:
  • HecTimeException: if offset it out of range for interval
def astimezone( self, time_zone: Union[HecTime, datetime.datetime, zoneinfo.ZoneInfo, str], on_tz_not_set: int = 1) -> HecTime:
@NoOpWarning
def clean_time(self) -> None:

Placeholder for API compatibility. Does nothing.

def clone(self) -> object:

Returns a clone of this object

Returns:

object: the clone of this object

def compare_times(self, other: HecTime) -> int:

Returns an integer comparison with another HecTime object

Arguments:
  • other (HecTime): The other HecTime object
Returns:

int:

  • -1 if this object < other
  • 0 if this object == other
  • 1 if this object > other
@NotImplementedWarning
def compare_to(self, other: object) -> Any:

Not supported in this implementation

def compute_number_intervals( self, other: HecTime, interval: Union[int, datetime.timedelta, Interval]) -> int:

Returns the number of complete intervals between this object and another specified HecTime object

Arguments:
  • other (HecTime): The other time to compute the number of intervals to
  • interval (Union[int, timedelta]): The interval size to compute the number of intervals for.

    • int - the minutes in a standard interval
    • timedelta - If equivalent to a standard interval, the same result as specifying the equivalent integer is returned. Otherwise the both HecTime objects are converted to datetime objects and the number of intervals is computed as `((other.datetime - self.datetime) / timesdelta')
Raises:
  • HecTimeException: if interval is a non-standard integer or if it is a nonstandard timedelta and either of this object or other is not convertable to a datetime object
Returns:

int: The number of complete intervals between this time and the other time.

def convert_time_zone( self, from_time_zone: Union[zoneinfo.ZoneInfo, str], to_time_zone: Union[zoneinfo.ZoneInfo, str], respect_daylight_saving: Optional[bool] = True) -> HecTime:

Converts this object from one time zone to another, optionally specifyintg that the target time zone does not observe Daylight Saving Time (DST). Only for HecTime objects convertable to datetime objects (between 01Jan0001, 00:00 and 31Dec9999, 23:59).

NOTE: The Java signatures for this method that operate on and return a copy of the HecTime object are not supported in this implementation. The astimezone() method can be used for that purpose.

Arguments:
  • from_time_zone (Union[ZoneInfo, str]): The time zone to convert from
  • to_time_zone (Union[ZoneInfo, str]): The target time zone
  • respect_daylight_saving (Optional[bool]): Specifies whether the target time zone. should observe DST. Defaults to True.
    • If True, the target time zone is used as specified
    • If False and the specified target time zone observes DST, then a time zone is found that has the same UTC offset as the specified target time zone but does not observe DST.
Returns:

HecTime: The modified object

Raises:
  • HecTimeException: - If respect_daylight_saving is True, to_time_zone observes DST and no equivalent time zone could be found that does not observer DST
    • If this object is not convertable to a datetime object
def convert_to_time_zone( self, time_zone: Union[HecTime, datetime.datetime, zoneinfo.ZoneInfo, datetime.timezone, str, NoneType], on_tz_not_set: int = 1) -> HecTime:

Returns a copy of this object at the spcified time zone

Arguments:
  • time_zone (Optional[Union["HecTime", datetime, ZoneInfo, timezone, str]]): The target time zone or object containg the target time zone.
    • Use None to remove time zone information without time conversion.
    • Use "local" to specify the system time zone.
  • on_tz_not_set (int, optional): Specifies behavior if this object has no time zone attached. Defaults to 1.
    • 0: Quietly behave as if this object had the local time zone attached.
    • 1: (default) Same as 0, but issue a warning.
    • 2: Raise an exception preventing objectes with out time zones attached from using this method.
Returns:

HecTime: A copy of this object at the specified time zone

def copy(self) -> HecTime:

Returns a copy of this object already cast as an HecTime

Returns:

HecTime: The copy

def date(self, style: Optional[int] = None) -> str:

Returns the date in the specified style

Base date styles
0: June 2, 198510:  June 2, 85100: JUNE 2, 1985110: JUNE 2, 85
1:  Jun 2, 198511:   Jun 2, 85101:  JUN 2, 1985111:  JUN 2, 85
2:  2 June 198512:   2 June 85102:  2 JUNE 1985112:   2 JUN 85
3:    June 198513:     June 85103:    JUNE 1985113:    JUNE 85
4:    02Jun198514:     02Jun85104:    02JUN1985114:    02JUN85
5:     2Jun198515:      2Jun85105:     2JUN1985115:     2JUN85
6:      Jun198516:       Jun85106:      JUN1985116:      JUN85
7:  02 Jun 198517:   02 Jun 85107:  02 JUN 1985117:  02 JUN 85
8:   2 Jun 198518:    2 Jun 85108:   2 JUN 1985118:   2 JUN 85
9:     Jun 198519:      Jun 85109:     JUN 1985119:     JUN 85
Extended date styles
-1:      6/2/85-11:    06/02/85-101:     6/2/1985-111: 06/02/1985
-2:      6-2-85-12:    06-02-85-102:     6-2-1985-112: 06-02-1985
               -13:  1985-06-02

NOTE that years that overflow four digits will not be truncated if using a style that shows four digits in the table (styles 0..9, 100..109, -113..-101 and -13). Other formats will continue to show only the last two digits of the year. In all cases a negative sign will be prepended to the year for negative years (whether two digits or more are shown).

Arguments:
  • style (Optional[int]): The date style to use. If not specified the default_date_style property is used
Returns:

str: The formatted date

def date_and_time(self, style: Optional[int] = None) -> str:

Returns a string representing the date and time in the specified style.

Arguments:
  • style (Optional[int]): The date style to use. If not specified the default_date_style property is used
Returns:

str: The formatted date and time. The date is generated using the style parameter (see date), which is separated from the time portion (with colons) (see time) by a comma and space

date_str: str

The object's current date string using the default_date_style

Operations:

Read Only

date_time_str: str

The object's current date and time string using the default_date_style

Operations:

Read

def datetime(self) -> Optional[datetime.datetime]:

Returns a datetime object equivalent to this object.

Returns:

datetime: The equivalent datetime object or None if this object's time is undefined

day: Optional[int]

The object's day of month, or None if undefined

Operations:

Read Only

def day_of_week(self) -> Optional[int]:

Returns the day of week (1 = Sunday -> 7 = Saturday) for this object.

NOTE: This differs from datetime.weekday() whch returns 0=Monday -> 6=Sunday.

Returns:

int: The day of week (1 = Sunday -> 7 = Saturday)

def day_of_week_name(self) -> Optional[str]:
def day_of_year(self) -> Optional[int]:

Returns the day of the year of this object (01Jan = 1)

Returns:

Optional[int]: The day of the year

default_date_style: int

The object's current default data style.

Operations:

Read/Write

defined: bool

Whether this object has been defined

Operations:

Read Only

def equal_to(self, other: HecTime) -> bool:

Returns whether this object is equivalent to another

Arguments:
  • other (Union["HecTime", datetime]): The object to compare to
Deprrecated:

Use == operator instead

Returns:

bool: The result of the comparison

def get_default_date_style(self) -> int:

Returns the default date style

Deprecated:

Use default_date_style property instead

Returns int: The default date style

def get_interval_offset(self, interval: Union[Interval, int]) -> Optional[int]:

Returns the number of minutes that the current object is after the top of the most recent standard interval

Arguments:
  • interval Union[Interval, int]: The interval to determine the offset into. If int, then the value is minutes.
Raises:
  • HecTimeException: if the interval is not a standard interval
Returns:

Optional[int]: The number of minutes into the interval

def get_iso_8601_date_time(self) -> str:

Returns the time of this object in ISO 8601 format.

Returns:

str: The time of this object in ISO 8601 format

def get_minutes( self, time_zone_offset: Union[int, zoneinfo.ZoneInfo, NoneType] = None) -> Optional[int]:

Returns the time of this object as (days since 1899) * 1400 + (minutes past midnight), optionally offsetting by a time zone

Arguments:
  • time_zone_offset (Optional[Union[int, ZoneInfo]]): if int, the number of minutes behind UTC (positive for western longitudes)
Returns:

int: The time in minutes

def get_shows_time_as_beginning_of_day(self) -> bool:

Retrieves whether midnight is shown as hour 0 instead of hour 24 of the previous day

Deprecated:

Use midnight_as_2400 property instead

Returns:

bool: True if midnight is shown as hour 0, False if midnight is shown as hour 24

def get_time(self, with_colons: Optional[bool] = True) -> str:

Returns a string representing the time portion

  • with_colons = True (default), [..., 6, 8, 23] is retuned is 06:08:23
  • with_colons = False, [..., 6, 8, 23] is retuned is 0608
Arguments:
  • with_colons (Optional[bool]): Specifies with or without colons. Defaults to True.
Deprecated:

use .HecTime.time">time method instead

Returns:

str: The time portion string with colons (hour, minute, and second), or without colons (hour, minute only))

def get_time_granularity(self) -> int:

Returns the granularity of this object

Deprecated:

Use granularity property instead

Returns:

int: The granularity

def get_time_in_millis( self, time_zone_offset: Union[int, zoneinfo.ZoneInfo, NoneType] = None) -> Optional[int]:

Returns the time of this object in milliseconds into of the Unix Epoch (01Jan1970 00:00:00 UTC).

Note that is the standard time value used in Java as well as 1000.0 times the standard time value used in python (e.g., time.time() or datetime.timestamp())

Arguments:
  • time_zone_offset (Optional[Union[int, ZoneInfo]]): if int, the number of minutes behind UTC (positive for western longitudes). If not specified, the milliseconds returned will be as if this object is in UTC
Returns:

Optional[int]: None if this object is not defined., otherwise the milliseconds of the current time from the beginning of the Unix Epoch

def get_xml_date_time(self) -> str:

Returns the time of this object in ISO 8601 format.

Deprecated:

Use get_iso_8601_date_time instead

Raises:
  • HecTimeException: if time_zone_offset is specifed but is not an integer or ZoneInfo object,
  • or is a ZoneInfo object and no UTC offset could be determined from it
Returns:

str: The time of this object in ISO 8601 format

granularity: int

The object's current granularity.

Operations:

Read/Write

Returns:

int: The granularity

def greater_than(self, other: HecTime) -> bool:

Returns whether this object is greater than (later than) another HecTime object

Arguments:
  • other (HecTime): The other object to compare to
Deprecated:

Use the the > operator instead.

Returns:

bool: Whether this object is greater than the other

def greater_than_equal_to(self, other: HecTime) -> bool:

Returns whether this object is greater than (later than) or equal to (same time as) another HecTime object

Arguments:
  • other (HecTime): The other object to compare to
Deprecated:

Use the the >= operator instead.

Returns:

bool: Whether this object is greater than or equal to the other

hour: Optional[int]

The object's hour of day, or None if undefined

Operations:

Read Only

def hour_minutes(self) -> str:

Returns the time portion in HHMM format or "" if this object is undefined

Returns:

str: The time portion in HHMM format or "" if this object is undefined

def hours_minutes_seconds(self, hours: list[int], minutes: list[int], seconds: list[int]) -> None:

Returns the object's hour, minute, and second in the spefied parameters

Arguments:
  • hours (list[int]): Element 0 recieves the hour
  • minutes (list[int]): Element 0 recieves the minute
  • seconds (list[int]): Element 0 receives the second
def increment( self, count: int, interval: Union[Interval, TimeSpan, datetime.timedelta, int]) -> HecTime:

Increments this object by a specified number of intervals.

For month-based intervals ("Tri-Month", "Semi-Month", "1Month", "1Year"), if the date of the current object is the last day of a month, the resulting date will be the last day of the month or sub-month (days 10 or 20 for "Tri-Month" and day 15 for "Semi-Month"), as shown:

Start TimeCountIntervalResult
28Feb2023, 01:001"Tri-Month"10Mar2023, 01:00
28Feb2023, 01:002"Tri-Month"20Mar2023, 01:00
28Feb2023, 01:003"Tri-Month"31Mar2023, 01:00
28Feb2024, 01:001"Tri-Month"08Mar2023, 01:00
28Feb2024, 01:002"Tri-Month"18Mar2023, 01:00
28Feb2024, 01:003"Tri-Month"28Mar2023, 01:00

Note that this method produces results that differ from the Java HecTime.increment() method where the Java code produces incorrect results, as in the following examples (all such discrepancies are limited to "Tri-Month", "Semi-Month", and "1Month":

Start TimeCountIntervalCorrect ResultJava HecTime Result
29Jan2023, 01:001"1Month"28Feb2023, 01:0001Mar2023, 01:00
09Feb2024, 01:002"Tri-Month"29Feb2024, 01:0009Mar2024, 01:00
28Feb2024, 01:002"Semi-Month"28Mar2024, 01:0031Mar2024, 01:00
Arguments:
  • count (int): The number of intervals to increment
  • interval (Union[Interval, TimeSpan, timedelta, int]): The interval to increment by. If int:
    • interpreted as a number of minutes
    • for standard intervals:
      • should be actual minutes for intervals <= 1Week
      • should characteristic minutes for intervals > 1Week
Returns:

HecTime: The incremented object

def increment_secs(self, count: int, interval: int) -> HecTime:

Increments this object by a specified number of intervals, which are specified in seconds

Arguments:
  • count (int): The number of intervals to increment
  • interval (int): The size of the interval in seconds. The behavior depends on whether the interval is < 60:
    • < 60 - the object is incremented by (count * interval) seconds
    • >= 60 - The object is incremented by (count * interval // 60) minutes
Returns:

HecTime: The incremented object

def is_defined(self) -> bool:

Returns whether this object has been defined

Deprecated:

Use defined property instead

Returns:

bool: Whether this object has been defined

def iso_date(self) -> str:

Returns the date of the current object as YYMMDD format

Returns:

str: The date in YYMMDD format

def iso_time(self) -> str:

Returns the time of the current object as HHMMSS format

Returns:

str: The date in HHMMSS format

def is_time_defined(self) -> bool:

Returns whether this object has been defined

Deprecated:

Use defined property instead

Returns:

bool: Whether this object has been defined

is_utc: bool
def label_as_time_zone( self, time_zone: Union[HecTime, datetime.datetime, zoneinfo.ZoneInfo, datetime.timezone, str, NoneType], on_already_set: int = 1) -> HecTime:

Attaches the specified time zone to this object. Does not change the time

Arguments:
  • time_zone (Optional[Union["HecTime", datetime, ZoneInfo, timezone, str]]): The time zone to attach or object containing that time zone. Use "local" to specify the system time zone.
  • on_already_set (int, optional): Specifies action to take if a different time zone is already attached. Defaults to 1.
    • 0: Quietly attach the new time zone
    • 1: (default) Issue a warning about attaching a different time zone
    • 2: Raises an exception
Raises:
  • HecTimeException: if a different time zone is already attached and on_already_set == 2
Returns:

HecTime: The updated object

def julian(self) -> Optional[int]:

Returns the number of days since 31Dec8199 for this object

Returns:

int: The number of days since 31Dec1899

def less_than(self, other: HecTime) -> bool:

Returns whether this object is less than (earlier than) another HecTime object

Arguments:
  • other (HecTime): The other HecTime object
Deprecated:

Use the < operator instead

Returns:

bool: Whether this object is less than the other object

def less_than_equal_to(self, other: HecTime) -> bool:

Returns whether this object is less than (earlier than) another or equal to (same time as) HecTime object

Arguments:
  • other (HecTime): The other HecTime object
Deprecated:

Use the <= operator instead

Returns:

bool: Whether this object is less than or equal to the other object

midnight_as_2400: bool

The object's current setting of whether to show midnight as hour 24 (default) or not.

Operations:

Read/Write

minute: Optional[int]

The object's minute of hour, or None if undefined

Operations:

Read Only

def minutes_since_midnight(self) -> Optional[int]:

Returns the number of minutes past midnight for this object

Returns:

int: the number of minutes past midnight

month: Optional[int]

The object's month, or None if undefined

Operations:

Read Only

def not_equal_to(self, other: HecTime) -> bool:

Returns whether this object is not equivalent to another

Arguments:
  • other (Union["HecTime", datetime]): The object to compare to
Deprrecated:

Use != operator instead

Returns:

bool: The result of the comparison

@staticmethod
def now(granularity: int = 11) -> HecTime:

Returns a new HecTime object initialized to the current system time and specified or default granularity

Arguments:
  • granularity (int, optional): The granularity of the new object. Defaults to MINUTE_GRANULARITY.
Returns:

HecTime: The newly created object

second: Optional[int]

The object's second of minute, or None if undefined

Operations:

Read Only

def seconds_since_midnight(self) -> int:

Returns the number of seconds past midnight for this object

Returns:

int: the number of seconds past midnight

def set(self, *args: Any) -> int:

Set the object to a specified date/time. Valid parameters are:

  • set(time_int: int) sets the time to the value of time_int for the current granularity
  • set(date_time_str: str) sets the time to the results of parse_date_time_str(date_time_str)
  • set(dt: datetime) sets the time to the value of dt
  • set(values: Union[list[int],tuple[int,...]]) sets the time to values
  • set(other_hectime: HecTime) sets the time and granularity to be the same as other_hectime
  • set(date_str: str, time_str: str) sets the time to the results of parse_date_time_str(date_str+" "+time_str)
Returns:

int: 0 if date/time is successfully set, otherwise non-zero

See Also:

parse_date_time_str()
HecTime.strptime()

def set_current(self) -> HecTime:

Sets this object to the current time

Returns:

HecTime: The modified object

def set_date(self, date_str: str) -> int:

Sets the date portion only from a string

Arguments:
  • date_str (str): The date string. Any time portion is ignored
Returns:

int: 0 on success or -1 on failure

def set_default_date_style(self, style: int) -> None:

Sets the default date style

Arguments:
  • style (int): The default date style
Deprecated:

Use default_date_style property instead

def set_julian( self, julian: int, minutes_since_midnight: Optional[int] = None, seconds_since_midnight: Optional[int] = None) -> HecTime:

Sets the date portion from the number of days since 1899, and optionally the time portion

Arguments:
  • julian (int): The number of days since 1899
  • minutes_since_midnight (Optional[int]): The number of minutes past midnight for the time portion. Defaults to None.
  • seconds_since_midnight (Optional[int]): The number of seconds past the minute for the time portion. Defaults to None.
Returns:

HecTime: The modified object

def set_minutes( self, total_minutes: int, time_zone_offset: Union[int, zoneinfo.ZoneInfo, NoneType]) -> HecTime:

Set the date and time portions of this object from the number of minutes since 1899

Arguments:
  • total_minutes (int): The number of minutes since 1899
  • time_zone_offset (Optional[Union[int, "ZoneInfo"]]): The time zone to represent this object in. Defaults to None. If int, the number of minutes behind UTC (positive for western longitudes)
Returns:

HecTime: The modified object

Raises:
  • HecTimeException: if time_zone_offset is not an integer or ZoneInfo object, or if the UTC offset cannot be determed for the ZoneInfo object
def set_seconds(self, total_seconds: int) -> HecTime:

Sets the date and time portions of this object from the number seconds since 1970-01-01T00:00:00Z

Arguments:
  • total_seconds (int): The number of seconds since 1970-01-01T00:00:00Z (same as Python timestamps and seconds of Unix Epoch)
Returns:

HecTime: The modified object

def set_time(self, time_str: str) -> int:

Set the time portion of this object from a time string with or without the date portion

Arguments:
  • time_str (str): the time string
Returns:

int: 0 on success or -1 if the time string cannot be parsed

def set_time_granularity(self, granularity: int) -> HecTime:

Sets the granularity, keeping the existing time values if possible

Arguments:
  • granularity (int): The new granularity
Deprecated:

Use granularity property instead

Returns:

HecTime: The modified object

@NotImplementedWarning
def set_time_granularity_seconds(self, granularity_in_seconds: int) -> None:

Not supported in this implementation

def set_time_in_millis( self, milliseconds: int, time_zone_offset: Union[int, zoneinfo.ZoneInfo, NoneType]) -> HecTime:

Sets the date and time portions of this object from the number milliseconds since 1970-01-01T00:00:00Z

Arguments:
  • milliseconds (int): The number of seconds since 1970-01-01T00:00:00Z (same as Java milliseconds and milliseconds of Unix Epoch)
  • time_zone_offset (Optional[Union[int, "ZoneInfo"]]): The time zone to represent this object in. Defaults to None. If int, the number of minutes behind UTC (positive for western longitudes)
Returns:

HecTime: The modified object

def set_undefined(self) -> HecTime:

Sets this object to the undefined state.

Returns:

HecTime: The modified object

def set_xml(self, date_time_str: str) -> int:

Sets this object from an ISO 8601 date/time string.

Arguments:
  • date_time_str (str): The date/time string
Deprecated:

The set() function handles this. Use it instead

Returns:

int: 0 on success, -1 otherwise

def set_year_month_day( self, year: int, month: int, day: int, minutes_since_midnight: Optional[int]) -> HecTime:

Sets the date portion from a year, month, and day, and optioally the time portion from minutes past midnight

Arguments:
  • year (int): The year
  • month (int): The month
  • day (int): The day
  • minutes_since_midnight (Optional[int]): The minutes past midnight
Returns:

HecTime: The modified object

def show_time_as_beginning_of_day(self, state: bool) -> HecTime:

Sets whether to show midnight as hour 0 instead of hour 24 of the previous day

Arguments:
  • state (bool): Whether to show midnight as hour 0 instead of hour 24 of the previous day
Deprecated:

Use midnight_as_2400 property instead

Returns:

HecTime: The modified object

def strftime(self, format: str) -> str:

Returns a string representing the date and time in the specified format.

Arguments:
  • format (str): The format string. Format specfics can be found here.
Returns:

str: The formatted date and time

See Also:
def strptime(self, date_time_str: str, format: str) -> HecTime:

Sets this object from a string representation and a matching format.

Arguments:
  • date_time_str (str): The string to parse.
  • format (str): The format describing the string. Format specfics can be found here.
Returns:

HecTime: The object updated from the string representation and formt.

See Also:

parse_date_time_str()
HecTime.set()

def subtract( self, other: Union[int, HecTime, TimeSpan, datetime.timedelta, str]) -> HecTime:

Subtracts an integer number of granules or HecTime object from this one

Arguments:
  • other (Union[int, "HecTime", TimeSpan, timedelta, str]): item to subtract
Deprecated:

Use the -= operator instead

Returns:

HecTime: The modified object

def subtract_days(self, days: int) -> HecTime:

Subtracts a number of days from the object

Arguments:
  • days (int): the number of days to subtract.
Returns:

HecTime: The modified object

def subtract_hours(self, hours: int) -> HecTime:

Subtracts a number of hours fram the object

Arguments:
  • hours (int): the number of hours to subtract.
Returns:

HecTime: The modified object

def subtract_minutes(self, minutes: int) -> HecTime:

Subtracts a number of minutes from the object

Arguments:
  • minutes (int): the number of minutes to subtract.
Returns:

HecTime: The modified object

def subtract_seconds(self, seconds: int) -> HecTime:

Subtracts a number of seconds from the object

Arguments:
  • seconds (int): the number of seconds to subtract.
Returns:

HecTime: The modified object

def time(self, with_colons: Optional[bool] = True) -> str:

Returns a string representing the time portion

  • with_colons = True (default), [..., 6, 8, 23] is retuned is 06:08:23
  • with_colons = False, [..., 6, 8, 23] is retuned is 0608
Arguments:
  • with_colons (Optional[bool]): Specifies with or without colons. Defaults to True.
Returns:

str: The time portion string with colons (hour, minute, and second), or without colons (hour, minute only))

def time_granularity(self) -> int:

Returns the granularity of this object

Deprecated:

Use granularity property instead

Returns:

int: The granularity

@NotImplementedWarning
def to_string(self, style: Optional[int]) -> Any:

Not supported in this implementation

tzinfo: Optional[zoneinfo.ZoneInfo]

The object's attached time zone

Operations:

Read Only

value: int

The object's current time integer.

Operations:

Read/Write

year: Optional[int]

The object's year, or None if undefined

Operations:

Read Only

values: Optional[list[int]]

The object's current time values ([year, month, day, hour, minute, second]).

This property is None when the value property is UNDEFINED_TIME

Operations:

Read/Write

class HecTimeException(builtins.Exception):

Exception specific to the hectime module

class Interval(hec.TimeSpan):

Class to hold information about time series recurrence intervals.

Intervals are a restriction of the TimeSpan base class that also hold extra information.

  • Restriction: At most one of years, months, days, hours, and minutes can be non-zero, and seconds must be zero.
  • Extension:
    • Each interval has a name that may be context specific.
    • Each also has a specified number of minutes:
      • For non-calendar-based intervals, the minutes are the actual number of minutes in the interval
      • For calendar-based intervals, the minutes are a characteristic number based on standard calendar items:
        • Tri-Month: minutes = 10 * 1440 = 14400
        • Semi-Month: minutes = 15 * 1440 = 21600
        • 1 Month: minutes = 30 * 1440 = 43200
        • 1 Year: minutes = 365 * 1440 = 525600
        • 1 Decade: minutes = 365 * 1440 * 10 = 5256000
        • 1 Century: minutes = 365 * 1440 * 100 = 52560000

Intervals should not need to be created by the user, as intervals for the following three contexts are created during initialization of the interval module:

  • CWMS Context: Contains Intervals used with CWMS
  • DSS Context: Contains Intervals used with HEC-DSS files
  • DSS Block Size Context: Contains Intervals for the record block sizes in HEC-DSS files

Each context has its own set of four static methods that retrieve Interval objects or their names:

  • get_anyContext()
  • get_anyContext_name()
  • get_allContext()
  • get_allContext_names()

Where Context is Cwms, Dss, or DssBlock.

There are similar static methods that retrieve Interval objects or their names from all contexts:

Interval( timespan: str, name: str, context: str, minutes: Optional[int] = None)

Initializer used by module

MINUTES: dict[str, int] = {'0': 0, 'Irr': 0, '~1Minute': 0, '~2Minutes': 2, '~3Minutes': 3, '~4Minutes': 4, '~5Minutes': 5, '~6Minutes': 6, '~10Minutes': 10, '~12Minutes': 12, '~15Minutes': 15, '~20Minutes': 20, '~30Minutes': 30, '~1Hour': 0, '~2Hours': 120, '~3Hours': 180, '~4Hours': 240, '~6Hours': 360, '~8Hours': 480, '~12Hours': 720, '~1Day': 0, '~2Days': 2880, '~3Days': 4320, '~4Days': 5760, '~5Days': 7200, '~6Days': 8640, '~1Week': 0, '~1Month': 0, '~1Year': 0, '1Minute': 1, '2Minutes': 2, '3Minutes': 3, '4Minutes': 4, '5Minutes': 5, '6Minutes': 6, '10Minutes': 10, '12Minutes': 12, '15Minutes': 15, '20Minutes': 20, '30Minutes': 30, '1Hour': 60, '2Hours': 120, '3Hours': 180, '4Hours': 240, '6Hours': 360, '8Hours': 480, '12Hours': 720, '1Day': 1440, '2Days': 2880, '3Days': 4320, '4Days': 5760, '5Days': 7200, '6Days': 8640, '1Week': 10080, '1Month': 43200, '1Year': 525600, 'IR-Day': 0, 'IR-Month': 0, 'IR-Year': 0, 'IR-Decade': 0, 'IR-Century': 0, '~2Minute': 0, '~3Minute': 0, '~4Minute': 0, '~5Minute': 0, '~6Minute': 0, '~10Minute': 0, '~12Minute': 0, '~15Minute': 0, '~20Minute': 0, '~30Minute': 0, '~2Hour': 0, '~3Hour': 0, '~4Hour': 0, '~6Hour': 0, '~8Hour': 0, '~12Hour': 0, '~2Day': 0, '~3Day': 0, '~4Day': 0, '~5Day': 0, '~6Day': 0, '2Minute': 2, '3Minute': 3, '4Minute': 4, '5Minute': 5, '6Minute': 6, '10Minute': 10, '12Minute': 12, '15Minute': 15, '20Minute': 20, '30Minute': 30, '2Hour': 120, '3Hour': 180, '4Hour': 240, '6Hour': 360, '8Hour': 480, '12Hour': 720, '2Day': 2880, '3Day': 4320, '4Day': 5760, '5Day': 7200, '6Day': 8640, 'Tri-Month': 14400, 'Semi-Month': 21600, '1Decade': 5256000, '1Century': 52560000}

Dictionary that holds interval minutes, accessed by interval name. Includes all contexts.

Click to show contents.

NameMinutesContext(s)
00CWMS
Irr0CWMS
IR-Century0DSS
IR-Day0DSS
IR-Decade0DSS
IR-Month0DSS
IR-Year0DSS
1Minute1CWMS, DSS
2Minute2DSS
2Minutes2CWMS
3Minute3DSS
3Minutes3CWMS
4Minute4DSS
4Minutes4CWMS
5Minute5DSS
5Minutes5CWMS
6Minute6DSS
6Minutes6CWMS
10Minute10DSS
10Minutes10CWMS
12Minute12DSS
12Minutes12CWMS
15Minute15DSS
15Minutes15CWMS
20Minute20DSS
20Minutes20CWMS
30Minute30DSS
30Minutes30CWMS
1Hour60CWMS, DSS
2Hour120DSS
2Hours120CWMS
3Hour180DSS
3Hours180CWMS
4Hour240DSS
4Hours240CWMS
6Hour360DSS
6Hours360CWMS
8Hour480DSS
8Hours480CWMS
12Hour720DSS
12Hours720CWMS
1Day1440CWMS, DSS
2Day2880DSS
2Days2880CWMS
3Day4320DSS
3Days4320CWMS
4Day5760DSS
4Days5760CWMS
5Day7200DSS
5Days7200CWMS
6Day8640DSS
6Days8640CWMS
1Week10080CWMS, DSS
Tri-Month14400DSS
Semi-Month21600DSS
1Month43200CWMS, DSS, DSS BLOCK SIZE
1Year525600CWMS, DSS, DSS BLOCK SIZE
1Decade5256000DSS BLOCK SIZE
1Century52560000DSS BLOCK SIZE

context: str

The context of this object ("Cwms", "Dss", or "DssBlock")

Operations:

Read-only

@staticmethod
def get_all( matcher: Optional[Callable[[Interval], bool]] = None, exception_on_not_found: Optional[bool] = None) -> list[Interval]:

Retuns list of matched Interval objects in the any context

Arguments:
  • matcher (Optional[Callable[[Interval], bool]]): A function that returns True or False when passed an Interval object parameter. Defaults to None. If None, all Interval objects in all contexts are matched.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
Returns:

List[Interval]: A list of matched Interval objects (may be empty)

@staticmethod
def get_all_cwms( matcher: Optional[Callable[[Interval], bool]] = None, exception_on_not_found: Optional[bool] = None) -> list[Interval]:

Retuns list of matched Interval objects in the CWMS context

Arguments:
  • matcher (Optional[Callable[[Interval], bool]]): A function that returns True or False when passed an Interval object parameter. Defaults to None. If None, all Interval objects in the context are matched.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

List[Interval]: A list of matched Interval objects (may be empty)

@staticmethod
def get_all_cwms_names( matcher: Optional[Callable[[Interval], bool]] = None, exception_on_not_found: Optional[bool] = None) -> list[str]:

Retuns list of names of matched Interval objects in the CWMS context

Arguments:
  • matcher (Optional[Callable[[Interval], bool]]): A function that returns True or False when passed an Interval object parameter. Defaults to None. If None, all Interval objects in the context are matched.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

List[str]: A list of names of matched Interval objects (may be empty)

@staticmethod
def get_all_dss( matcher: Optional[Callable[[Interval], bool]] = None, exception_on_not_found: Optional[bool] = None) -> list[Interval]:

Retuns list of matched Interval objects in the DSS context

Arguments:
  • matcher (Optional[Callable[[Interval], bool]]): A function that returns True or False when passed an Interval object parameter. Defaults to None. If None, all Interval objects in the context are matched.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

List[Interval]: A list of matched Interval objects (may be empty)

@staticmethod
def get_all_dss_block_names( matcher: Optional[Callable[[Interval], bool]] = None, exception_on_not_found: Optional[bool] = None) -> list[str]:

Retuns list of names of matched Interval objects in the DSS block size context

Arguments:
  • matcher (Optional[Callable[[Interval], bool]]): A function that returns True or False when passed an Interval object parameter. Defaults to None. If None, all Interval objects in the context are matched.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

List[str]: A list of names of matched Interval objects (may be empty)

@staticmethod
def get_all_dss_blocks( matcher: Optional[Callable[[Interval], bool]] = None, exception_on_not_found: Optional[bool] = None) -> list[Interval]:

Retuns list of matched Interval objects in the DSS block size context

Arguments:
  • matcher (Optional[Callable[[Interval], bool]]): A function that returns True or False when passed an Interval object parameter. Defaults to None. If None, all Interval objects in the context are matched.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

List[Interval]: A list of matched Interval objects (may be empty)

@staticmethod
def get_all_dss_names( matcher: Optional[Callable[[Interval], bool]] = None, exception_on_not_found: Optional[bool] = None) -> list[str]:

Retuns list of names of matched Interval objects in the DSS context

Arguments:
  • matcher (Optional[Callable[[Interval], bool]]): A function that returns True or False when passed an Interval object parameter. Defaults to None. If None, all Interval objects in the context are matched.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

List[str]: A list of names of matched Interval objects (may be empty)

@staticmethod
def get_all_names( matcher: Optional[Callable[[Interval], bool]] = None, exception_on_not_found: Optional[bool] = None) -> list[str]:

Retuns list of names of matched Interval objects in the any context

Arguments:
  • matcher (Optional[Callable[[Interval], bool]]): A function that returns True or False when passed an Interval object parameter. Defaults to None. If None, all Interval objects in all contexts are matched.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
Returns:

List[str]: A list of names of matched Interval objects (may be empty)

@staticmethod
def get_any( matcher: Callable[[Interval], bool], exception_on_not_found: Optional[bool] = None) -> Optional[Interval]:

Retuns a matched Interval object in any context

Arguments:
  • matcher (Callable[[Interval], bool]): A function that returns True or False when passed an Interval object parameter.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

Optional[Interval]: A matched Interval object or None

@staticmethod
def get_any_cwms( matcher: Callable[[Interval], bool], exception_on_not_found: Optional[bool] = None) -> Optional[Interval]:

Retuns a matched Interval object in the CWMS context, or None if there is no such object

Arguments:
  • matcher (Callable[[Interval], bool]): A function that returns True or False when passed an Interval object parameter.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_no_not_found and get_default_exception_on_not_found
Returns:

Optional[Interval]: A matched Interval object or None

@staticmethod
def get_any_cwms_name( matcher: Callable[[Interval], bool], exception_on_not_found: Optional[bool] = None) -> Optional[str]:

Retuns the name of a matched Interval object in the CWMS context, or None if there is no such object

Arguments:
  • matcher (Callable[[Interval], bool]): A function that returns True or False when passed an Interval object parameter.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

Optional[str]: The name of a matched Interval object or None

@staticmethod
def get_any_dss( matcher: Callable[[Interval], bool], exception_on_not_found: Optional[bool] = None) -> Optional[Interval]:

Retuns a matched Interval object in the DSS context, or None if there is no such object

Arguments:
  • matcher (Callable[[Interval], bool]): A function that returns True or False when passed an Interval object parameter.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

Optional[Interval]: A matched Interval object or None

@staticmethod
def get_any_dss_block( matcher: Callable[[Interval], bool], exception_on_not_found: Optional[bool] = None) -> Optional[Interval]:

Retuns a matched Interval object in the DSS block size context, or None if there is no such object

Arguments:
  • matcher (Callable[[Interval], bool]): A function that returns True or False when passed an Interval object parameter.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

Optional[Interval]: A matched Interval object or None

@staticmethod
def get_any_dss_block_name( matcher: Callable[[Interval], bool], exception_on_not_found: Optional[bool] = None) -> Optional[str]:

Retuns the name of a matched Interval object in the DSS block size context, or None if there is no such object

Arguments:
  • matcher (Callable[[Interval], bool]): A function that returns True or False when passed an Interval object parameter.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

Optional[str]: The name of a matched Interval object or None

@staticmethod
def get_any_dss_name( matcher: Callable[[Interval], bool], exception_on_not_found: Optional[bool] = None) -> Optional[str]:

Retuns the name of a matched Interval object in the DSS context, or None if there is no such object

Arguments:
  • matcher (Callable[[Interval], bool]): A function that returns True or False when passed an Interval object parameter.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_exception_on_not_found and get_default_exception_on_not_found
Returns:

Optional[str]: The name of a matched Interval object or None

@staticmethod
def get_any_name( matcher: Callable[[Interval], bool], exception_on_not_found: Optional[bool] = None) -> Optional[str]:

Retuns the name of a matched Interval object in the any context, or None if there is no such object

Arguments:
  • matcher (Callable[[Interval], bool]): A function that returns True or False when passed an Interval object parameter.
    Examples:
    • lambda i : i.is_irregular
    • lambda i : i.minutes < 60
    • lambda i : i.name.find("Week") != -1
  • exception_on_not_found (bool): Specifies whether to raise an exception if no Intervals are found. If None, the default behavior is used. Optional. Defaults to None. See set_default_excpetion_on_not_found and get_default_exception_on_not_found
Returns:

Optional[str]: The name of a matched Interval object or None

@staticmethod
def get_cwms(key: Union[str, int]) -> Interval:

Returns a CWMS interval with the specified name or minutes

Arguments:
  • key (Union[str, int]): The name or (actual or characteristic) minutes of the interval to retrieve.
Raises:
  • IntervalException: if no CWMS interval exists with the specified key
  • TypeError: If the key is not a string or integer
Returns:

Interval: The CWMS interval

def get_datetime_index( self, start_time: Any, end_time: Optional[Any] = None, count: Optional[int] = None, offset: Optional[Any] = None, time_zone: Optional[Any] = None, name: Optional[str] = None) -> pandas.core.indexes.datetimes.DatetimeIndex:

Generates a pandas DatetimeIndex from this interval.

Arguments:
  • start_time (Any): A time in the first interval. If offset is None, this will be the first time, otherwise the first time will be the top of the interval containing this time plus the specified offset. If the time includes no time zone, it will be assumed to be in time_zone, if specified, if any. Must be an HecTime object or an object suitable for the HecTime constructor
  • end_time (Optional[Any]): The generated series will end on or before this time, if specified. If the time includes no time zone, it will be assumed to be in time_zone, if specified. If specified, must be an HecTime object or an object suitable for the HecTime constructor. Either end_time or count, but not both, must be specified. Defaults to None.
  • count (Optional[int]): The number of times in the index. Either end_time or count, but not both, must be specified. Defaults to None.
  • offset (Optional[Any]): The offset of each time into the interval. If None, the offset is determined from start_time. If specified, must be an TimeSpan object or an object suitable for the TimeSpan constructor. Defaults to None.
  • time_zone (Optional[Any]): The time zone of the generated times. Must be specified if the interval is a local-regular interval. Defaults to None.
  • name (Optional[str]): The name of the index. If the generated index is to be used in a TimeSeries object, specify the name as "name". Defaults to None.
Raises:
  • IntervalException: If invalid parameters are specified
Returns:

pd.DatetimeIndex: The generated index.

Notes:

There is a somewhat subtle interplay between start_time and offset. If offset is None or not specified, the index is generated as follows:

  • The offset used is the offset of start_time into the Interval object being used
  • The offset handles end-of-month dates and leap years by adjusting the actual offset at each time to keep dates as aligned as possible

Otherwise the offset is used literally.
See the following examples:

Index on 1Month interval
Values in red exceed the end of the month
start_time"2025‑01‑31 08:00:00""2025‑01‑01 00:00:00"
offsetNoneTimeSpan("P30DT8H")timedelta(
  days=30,
  hours=8,
)
index
2025‑01‑31 08:00:002025‑01‑31 08:00:002025‑01‑31 08:00:002025‑01‑31 08:00:00
2025‑02‑28 08:00:002025‑03‑03 08:00:002025‑03‑03 08:00:002025‑03‑03 08:00:00
2025‑03‑31 08:00:002025‑03‑31 08:00:002025‑03‑31 08:00:002025‑03‑31 08:00:00
2025‑04‑30 08:00:002025‑05‑01 08:00:002025‑05‑01 08:00:002025‑05‑01 08:00:00
2025‑05‑31 08:00:002025‑05‑31 08:00:002025‑05‑31 08:00:002025‑05‑31 08:00:00
2025‑06‑30 08:00:002025‑07‑01 08:00:002025‑07‑01 08:00:002025‑07‑01 08:00:00
2025‑07‑31 08:00:002025‑07‑31 08:00:002025‑07‑31 08:00:002025‑07‑31 08:00:00
2025‑08‑31 08:00:002025‑08‑31 08:00:002025‑08‑31 08:00:002025‑08‑31 08:00:00
2025‑09‑30 08:00:002025‑10‑01 08:00:002025‑10‑01 08:00:002025‑10‑01 08:00:00
2025‑10‑31 08:00:002025‑10‑31 08:00:002025‑10‑31 08:00:002025‑10‑31 08:00:00
2025‑11‑30 08:00:002025‑12‑01 08:00:002025‑12‑01 08:00:002025‑12‑01 08:00:00
2025‑12‑31 08:00:002025‑12‑31 08:00:002025‑12‑31 08:00:002025‑12‑31 08:00:00
Index on 1Year interval
Values in red don't match the starting day-of-month
start_time"2025‑05‑11 00:00:00""2025‑01‑01 00:00:00"
offsetNoneTimeSpan("P1M10D")timedelta(
  days=130,
)
index
2025‑05‑11 00:00:002025‑05‑11 00:00:002025‑05‑11 00:00:002025‑05‑11 00:00:00
2026‑05‑11 00:00:002026‑05‑11 00:00:002026‑05‑11 00:00:002026‑05‑11 00:00:00
2027‑05‑11 00:00:002027‑05‑11 00:00:002027‑05‑11 00:00:002027‑05‑11 00:00:00
2028‑05‑11 00:00:002028‑05‑11 00:00:002028‑05‑11 00:00:002028‑05‑10 00:00:00
2029‑05‑11 00:00:002029‑05‑11 00:00:002029‑05‑11 00:00:002029‑05‑11 00:00:00
2030‑05‑11 00:00:002030‑05‑11 00:00:002030‑05‑11 00:00:002030‑05‑11 00:00:00
2031‑05‑11 00:00:002031‑05‑11 00:00:002031‑05‑11 00:00:002031‑05‑11 00:00:00
2032‑05‑11 00:00:002032‑05‑11 00:00:002032‑05‑11 00:00:002032‑05‑10 00:00:00
2033‑05‑11 00:00:002033‑05‑11 00:00:002033‑05‑11 00:00:002033‑05‑11 00:00:00
2034‑05‑11 00:00:002034‑05‑11 00:00:002034‑05‑11 00:00:002034‑05‑11 00:00:00
2035‑05‑11 00:00:002035‑05‑11 00:00:002035‑05‑11 00:00:002035‑05‑11 00:00:00
2036‑05‑11 00:00:002036‑05‑11 00:00:002036‑05‑11 00:00:002036‑05‑10 00:00:00
@staticmethod
def get_default_exception_on_not_found() -> bool:

Retrieves the default behavior if any of the get... methods do not find an Interval object to return.

Returns:

bool: True if the default behavior is to raise an exception when no Interval is found or False if None is returned when no Interval is found

@staticmethod
def get_dss(key: Union[str, int]) -> Interval:

Returns an HEC-DSS interval with the specified name or minutes

Arguments:
  • key (Union[str, int]): The name or (actual or characteristic) minutes of the interval to retrieve.
Raises:
  • IntervalException: if no Dss interval exists with the specified key
  • TypeError: If the key is not a string or integer
Returns:

Interval: The Dss interval

@staticmethod
def get_dss_block_for_interval( interval: Union[str, int, Interval]) -> Interval:

Returns the HEC-DSS block size for a specified interval.

Arguments:
  • interval (Union[str, int, "Interval"]): The interval to return the block size for. May be an Interval object, or its name or (actual or characteristic) minutes.
Returns:

Interval: An interval object representing the HEC-DSS block size

is_any_irregular: bool

Whether this object represents a normal irregular or pseudo-regular interval

Operations:

Read-only

is_any_regular: bool

Whether this object represents a regular or local regular interval

Operations:

Read-only

is_local_regular: bool

Whether this object represents a local regular interval

Operations:

Read-only

is_pseudo_regular: bool

Whether this object represents a pseudo-regular interval

Operations:

Read-only

is_regular: bool

Whether this object represents a normal regular interval

Operations:

Read-only

is_irregular: bool

Whether this object represents a normal irregular interval

Operations:

Read-only

minutes: int

The minutes (actual or characteristic) of this object

Operations:

Read-only

name: str

The name of this object

Operations:

Read-only

@staticmethod
def set_default_exception_on_not_found(state: bool) -> None:

Sets the default behavior if any of the get... methods do not find an Interval object to return.

Arguments:
  • state (bool): Whether to raise an exception if no Interval is found (True) or return None (False)
class IntervalException(hec.TimeSpanException):

Exception specific to Interval operations

class Location:

Holds information about locations

Location( name: str, office: Optional[str] = None, latitude: Optional[float] = None, longitude: Optional[float] = None, horizontal_datum: Optional[str] = None, elevation: Optional[float] = None, elevation_unit: Optional[str] = None, vertical_datum: Optional[str] = None, time_zone: Optional[str] = None, kind: Optional[str] = None, vertical_datum_info: Union[str, dict[str, Any], NoneType] = None, **other_info)

Initializes a Location object

Arguments:
  • name (str): The location name
  • office (Optional[str]): The office that owns the location, if applicable. Defaults to None.
  • latitude (Optional[float]): The latitude of the location. Defaults to None.
  • longitude (Optional[float]): The longitude of the location. Defaults to None.
  • horizontal_datum (Optional[str]): The horizontal datum of the specified lat/lon. Defaults to None.
  • elevation (Optional[float]): The elevation of the location. Defaults to None.
  • elevation_unit (Optional[str]): The unit of elevation of the location. Defaults to None.
  • vertical_datum (Optional[str]): The native vertical datum of the specified elevation. Defaults to None.
  • vertical_datum_info (Optional[Union[str, dict[str,Any]]]): The vertical datum info for the location. Overrides elevation, elevation_unit, and vertical_datum parameters, if also specified. Defaults to None.
  • other_info (Optional[dict[str,Any]]): Optional dictionary of other location info. Is accessible via other_info property
basename: str

The name of the location up to any initial '-' character

Operations:

Read Only

def copy(self) -> Location:
elevation: Optional[UnitQuantity]

The elevation of the location

Operations:

Read/Write

horizontal_datum: Optional[str]

The horizontal datum of the location's latitude/longitude

Operations:

Read/Write

kind: Optional[str]

The kind of the location

Operations:

Read/Write

latitude: Optional[float]

The latitude of the location

Operations:

Read/Write

longitude: Optional[float]

The longitude of the location

Operations:

Read/Write

name: str

The full name of the location

Operations:

Read/Write

office: Optional[str]

The office that owns the location

Operations:

Read/Write

other_info: Optional[dict[str, Any]]

Dictionary of information provided to initializer.

Operations:

Read-Only

subname: Optional[str]

The name of the location after any initial '-' character

Operations:

Read Only

time_zone: Optional[str]

The time zone of the location

Operations:

Read/Write

vertical_datum: Optional[str]

The native vertical datum of the location's elevation

Operations:

Read/Write

vertical_datum_info: Optional[hec.parameter.ElevParameter._VerticalDatumInfo]

The vertical datum information for the location. * The getter returns a _VerticalDatumInfo object. * The setter accepts _VerticalDatumInfo objects

Operations:

Read/Write

vertical_datum_json: Optional[str]

The vertical datum info of the location, if any, as a JSON object

Operations:

Read-Only

vertical_datum_xml: Optional[str]

The vertical datum info of the location, if any, as an XML instance

Operations:

Read-Only

class LocationException(builtins.Exception):

Exception specific to Location operations

class Parameter:

Holds info (name and unit) for a parameter.

See base_parameter_definitions for information on base parameters and their conversions.

Parameter(name: str, unit_or_system: Optional[str] = None)

Initializer

Arguments:
  • name (str): The full parmeter name
  • unit_or_system (Optional[str]):
    • If EN or None, the default English unit for the base parameter will be assigned
    • if SI, the default Système International unit for the base parameter will be assigned
    • Otherwise the specified unit will be assigned
Raises:
  • ParameterException: If the parameter name does not contain a valid base parameter name, or if the specified unit is not valid for the parameter
  • KeyError: If the specified unit is not a valid unit name, alias or Pint unit definition
@staticmethod
def accumulatable_base_parameters(context: str = 'CWMS') -> List[str]:

Returns a list of base parameter names that can be accumulated over time for the specified context

See base_parameter_definitions for information on base parameters and their conversions.

Arguments:
  • context (str): The context for the base parameter names. Currently only "CWMS" is supported. Defaults to "CWMS"
Raises:
  • ParameterException: If an invalid context is specified
Returns:

List[str]: A sorted list of names of base parameter that can be integrated over time for the context

base_parameter: str

The actual base parameter used. Will be same as basename unless the parameter was created using a parameter alias

Operations:

Read Only

@staticmethod
def base_parameters(context: str = 'CWMS') -> List[str]:

Returns a list of valid base parameter names for the specified context

See base_parameter_definitions for information on base parameters and their conversions.

Arguments:
  • context (str): The context for the base parameter names. Currently only "CWMS" is supported. Defaults to "CWMS"
Raises:
  • ParameterException: If an invalid context is specified
Returns:

List[str]: A sorted list of valid base parameter names for the context

basename: str

The name of the parameter as specified up to any initial '-' character

Operations:

Read Only

@staticmethod
def differentiable_base_parameters(context: str = 'CWMS') -> List[str]:

Returns a list of base parameter names that can be differentiated with respect to time for the specified context

See base_parameter_definitions for information on base parameters and their conversions.

Arguments:
  • context (str): The context for the base parameter names. Currently only "CWMS" is supported. Defaults to "CWMS"
Raises:
  • ParameterException: If an invalid context is specified
Returns:

List[str]: A sorted list of names of base parameter that can be differentiated with respect to time for the context

@staticmethod
def differentiation_info(base_parameter: str, context: str = 'CWMS') -> dict[str, typing.Any]:

Returns differentiation information for a base parameter name

See base_parameter_definitions for information on base parameters and their conversions.

Arguments:
  • base_parameter (str): The base parameter to get the information for.
  • context (str): The context for the base parameter names. Currently only "CWMS" is supported. Defaults to "CWMS"
Returns:

dict: A dictionary with the following content: { "base_parameter": , "EN" : , "SI" : , }

def get_compatible_units(self) -> list[str]:

Returns the list of unit names compatible with this parameter's unit

Returns:

list[str]: The list of compatible unit names

@staticmethod
def integrable_base_parameters(context: str = 'CWMS') -> List[str]:

Returns a list of base parameter names that can be integrated over time for the specified context

See base_parameter_definitions for information on base parameters and their conversions.

Arguments:
  • context (str): The context for the base parameter names. Currently only "CWMS" is supported. Defaults to "CWMS"
Raises:
  • ParameterException: If an invalid context is specified
Returns:

List[str]: A sorted list of names of base parameter that can be integrated over time for the context

def ito(self, unit_or_system: str) -> Parameter:

Assigns a unit to this parameter.

Identical to calling .to(unit_or_system, in_place=True)

Arguments:
  • unit_or_system (str):
    • If EN, the default English unit for the base parameter will be assigned
    • if SI, the default Système International unit for the base parameter will be assigned
    • Otherwise the specified unit will be assigned
Raises:
  • ParameterException: If the specified unit is not valid for the parameter
Returns:

Parameter: The converted object

name: str

The full name of the parameter as specified

Operations:

Read Only

subname: Optional[str]

The name of the parameter as specified after any initial '-' character

Operations:

Read Only

def to( self, unit_or_system: str, in_place: bool = False) -> Parameter:

Assigns a unit to this parameter or a copy of this parameter

Arguments:
  • unit_or_system (str):
    • If EN, the default English unit for the base parameter will be assigned
    • if SI, the default Système International unit for the base parameter will be assigned
    • Otherwise the specified unit will be assigned
  • in_place (bool, optional): Specifies whether to modify and return this object (True) or a copy of this object (False). Defaults to False.
Raises:
  • ParameterException: If the specified unit is not valid for the parameter
Returns:

Parameter: The converted object (self if in_place == True, otherwise a converted copy)

unit: pint.registry.Unit

The unit assigned to the parameter

Operations:

Read Only

unit_name: str

The unit name assigned to the parameter

Operations:

Read Only

class ParameterException(builtins.Exception):

Exception specific to Parameter operations

class ParameterType:

Holds info about parameter types.

Parameter types have 3 separate contexts, RAW, CWMS, and DSS. There's not much use for the RAW context except for providing a bridge between the CWMS and DSS contexts. Users would normally work in either the CWMS or DSS context.

The contexts of already-instantiated objects can also be set.

Parameter type names in the different contexts are:

RAWCWMSDSS
TotalTotalPER-CUM
MaximumMaxPER-MAX
MinimumMinPER-MIN
ConstantConstCONST
AverageAvePER-AVER
InstantaneousInstINST-CUM (for Precip or Count)
INST-VAL (for others)
ParameterType(param_type: str, context: Optional[str] = None)

Initializes a ParameterType object

Arguments:
  • param_type (str): The name of the parameter type
Raises:
  • ParameterTypeException: If param_type is not one of the values listed in the table above (context-insensitive)
context: str

The context of this object

Operations:

Read Only

def get_cwms_name(self) -> str:

Returns the name of the parameter time for the CWMS context

Returns:

str: The CWMS context name

def get_dss_name(self, is_precip: bool = False) -> str:

Returns the name of the parameter time for the DSS context

Arguments:
  • is_precip (bool, optional): Whether the parameter type is for a precipitation parameter. This matters only for the Instantaneous parameter type (CWMS=Inst). Defaults to False.
    • False: INST-CUM
    • True : INST-VAL
Returns:

str: The DSS context name

def get_raw_name(self) -> str:

Returns the name of the parameter time for the RAW context

Returns:

str: The RAW context name

name: str

The context-specific name of the object

Operations:

Read Only

@staticmethod
def parameter_type_names(context: str) -> List[str]:

Returns a list of valid parameter type names for the context.

Arguments:
  • context (str): The context for the parameter type names. Currently only "RAW", "CWMS", "DSS", and "ALL" are supported.
  • If "RAW", the parameter types for all contexts are returned
Raises:
  • ParameterTypeException: If an invlid context is specified
Returns:

List[str]: A sorted list of valid parameter type names for the context

def set_context(self, context: str) -> None:

Sets the context for this object

Arguments:
  • context (str): The context - must be one of RAW, CWMS, or DSS
Raises:
  • ParameterTypeException: If the specified context isn't one of the valid values
@classmethod
def set_default_context(cls, context: str) -> None:

Sets the default context for new ParameterType objects

Arguments:
  • context (str): The default context (RAW, CWMS, or DSS)
Raises:
  • ParameterTypeException: If an invalid context is specified
class ParameterTypeException(builtins.Exception):

Exception specific to ParameterType operations

@total_ordering
class Quality:

Holds a quality code and provides quality tests and operations

Quality(init_from: Any = 0)

Initializes a Quality object

Arguments:
  • init_from (Any, optional): The object to initialize from. Defaults to 0.
    • Not specified: the quality code is set to 0
    • Integer: the quality code is set to the integer
    • String: the quality code is set from the unique beginning of one of the following (case insensitive):
      • "Unscreened": the quality code is 0 (Unscreened)
      • "Unknown" or "Indeterminate": the quality code is 1 (Screened Indeterminate)
      • "Okay": the quality code is 3 (Screened Okay)
      • "Missing": the quality code is 5 (Screened Missing)
      • "Questionable": the quality code is 9 (Screened Questionable)
      • "Rejected": the quality code is 17 (Screened Rejected)
    • Quality: the quality code is set to the other object's quality code
    • List or tuple: the quality code is set from the list of component identifiers.
      The zero value can be set for any of the component by setting its identifier to None.
      The sequence must have a mininum length of 8, in this order:
      • screened identifier
      • validity identifier
      • range identifier
      • changed identifier
      • replacement cause identifier
      • replacement method identifier
      • test failed identifier (may be multiple identifiers concatenated with + character)
      • protected identifier
def add_test_failed(self, value: Union[int, str]) -> Quality:

Adds a failed test to the test failed component of this object from a code or identifier and returns the modified object

Arguments:
  • value (Union[int, str]): The test failed component code or identifier of the failed test to be added
Returns:

Quality: The modified object

changed: int

The changed component code of the quality code

Operations:

Read-Write

changed_id: str

The changed component identifier of the quality code

Operations:

Read-Write

code: int

The internal quality code as a signed or unsigned integer depending on the default setting.

See

Operations:

Read Only

protection: int

The protection component code of the quality code

Operations:

Read-Write

protection_id: str

The protection component identifier of the quality code

Operations:

Read-Write

range: int

The range component code of the quality code

Operations:

Read-Write

range_id: str

The range component identifier of the quality code

Operations:

Read-Write

def remove_test_failed(self, value: Union[int, str]) -> Quality:

Removes a failed test from the test failed component of this object from a code or identifier and returns the modified object

Arguments:
  • value (Union[int, str]): The test failed component code or identifier of the failed test to be removed
Returns:

Quality: The modified object

repl_cause: int

The replacement cause component code of the quality code

Operations:

Read-Write

repl_cause_id: str

The replacement cause component identifier of the quality code

Operations:

Read-Write

repl_method: int

The replacement method component code of the quality code

Operations:

Read-Write

repl_method_id: str

The replacement method component identifier of the quality code

Operations:

Read-Write

score: int

A score to compare qualities by:

ScreenedValidity CodeScore
UNSCREENEDUNKNOWN1
SCREENEDMISSING0
SCREENEDREJECTED0
SCREENEDUNKNOWN2
SCREENEDQUESTIONABLE3
SCREENEDOKAY4
Operations:

Read Only

screened: int

The screened component code of the quality code

Operations:

Read-Write

screened_id: str

The screened component identifier of the quality code

Operations:

Read-Write

def set_changed(self, value: Union[int, str]) -> Quality:

Sets the changed component of this object from a code or identifier and returns the modified object.

Using this method instead of setting the changed or changed_id properties allows chained operations.

Arguments:
  • value (Union[int, str]): The changed component code or identifier
Returns:

Quality: The modified object

def set_protection(self, value: Union[int, str]) -> Quality:

Sets the protection component of this object from a code or identifier and returns the modified object.

Using this method instead of setting the protection or protection_id properties allows chained operations.

Arguments:
  • value (Union[int, str]): The protection component code or identifier
Returns:

Quality: The modified object

def set_range(self, value: Union[int, str]) -> Quality:

Sets the range component of this object from a code or identifier and returns the modified object.

Using this method instead of setting the range or range_id properties allows chained operations.

Arguments:
  • value (Union[int, str]): The range component code or identifier
Returns:

Quality: The modified object

def set_repl_cause(self, value: Union[int, str]) -> Quality:

Sets the replacement cause component of this object from a code or identifier and returns the modified object.

Using this method instead of setting the repl_cause or repl_cause_id properties allows chained operations.

Arguments:
  • value (Union[int, str]): The replacement cause component code or identifier
Returns:

Quality: The modified object

def set_repl_method(self, value: Union[int, str]) -> Quality:

Sets the replacement method component of this object from a code or identifier and returns the modified object.

Using this method instead of setting the repl_method or repl_method_id properties allows chained operations.

Arguments:
  • value (Union[int, str]): The replacement method component code or identifier
Returns:

Quality: The modified object

def set_screened(self, value: Union[int, str]) -> Quality:

Sets the screened component of this object from a code or identifier and returns the modified object.

Using this method instead of setting the screened or screened_id properties allows chained operations.

Arguments:
  • value (Union[int, str]): The screened component code or identifier
Returns:

Quality: The modified object

def set_test_failed(self, value: Union[int, str]) -> Quality:

Sets the test failed component of this object from a code or identifier and returns the modified object.

Using this method instead of setting the test_failed or test_failed_id properties allows chained operations.

Arguments:
  • value (Union[int, str]): The test failed component code or identifier
Returns:

Quality: The modified object

def set_validity(self, value: Union[int, str]) -> Quality:

Sets the validity component of this object from a code or identifier and returns the modified object.

Using this method instead of setting the validity or validity_id properties allows chained operations.

Arguments:
  • value (Union[int, str]): The validity component code or identifier
Returns:

Quality: The modified object

@classmethod
def set_return_signed_codes(cls, state: bool = True) -> None:

Sets the type (signed or unsigned of the code property)

Arguments:
  • state (bool, optional): Sets default type to signed if true, otherwise unsigned. Defaults to True.
@classmethod
def set_return_unsigned_codes(cls, state: bool = True) -> None:

Sets the type (signed or unsigned of the code property)

Arguments:
  • state (bool, optional): Sets default type to unsigned if true, otherwise signed. Defaults to True.
signed: int

The internal quality code as a signed integer.

Operations:

Read Only

symbol: str

The text symbol of the quality.

The symbol will be one or two characters, with the first character being:

  • ~: Not screened
  • u or 'U': Screened, validity is unknown
  • o or O: Screened, validity is okay
  • m or M: Screened, validity is missing
  • q or Q: Screened, validity is questioned
  • r or R: Screened, validity is rejected

If a screened quality has the protection bit set, the first chanacter will be uppercase; if not, it will be lowercase.

A second character of + signifies that the quality has additional information about one or more of the following:

  • value range
  • value replacement cause and method
  • test(s) failed

This property is used when the quality is used in a string context (e.g., print(q))

Operations:

Read Only

test_failed: int

The test failed component code of the quality code

Operations:

Read-Write

test_failed_id: str

The test failed component identifier of the quality code

Operations:

Read-Write

text: str

The text description of the quality.

A space separated list of words specifying the state of the following, in order:

  • Screened: ("Unscreened" or "Screened")
  • Validity: ("Unknown", "Okay", "Missing", "Questionable", or "Rejected")
  • Range: ("No_range", "Range_1", "Range_2", or "Range_3")
  • Changed: ("Original" or "Modified")
  • Replacement Cause: ("None", "Automatic", "Interactive", "Manual", "Restored")
  • Replacement Method: ("None", "Lin_Interp", "Explicit", "Missing", "Graphical")
  • Test Failed: ("None" or one or more of the following concatenated with "+"):
    • "Absolute_Value"
    • "Constant_Value"
    • "Rate_Of_Change"
    • "Relative_Value"
    • "Duration_Value"
    • "Neg_Increment"
    • "Skip_List"
    • "User_Defined"
    • "Distribution"
  • Protection: ("Unprotected" or "Protected")
Operations:

Read Only

unsigned: int

The internal quality code as an unsigned integer.

Operations:

Read Only

validity: int

The validity component code of the quality code

Operations:

Read-Write

validity_id: str

The validity component identifier of the quality code

Operations:

Read-Write

class QualityException(builtins.Exception):

Common base class for all non-exit exceptions.

class Safety(enum.Enum):

Enumeration for specifying behavior of potentially unsafe operations.

NOOP_ON_UNSAFE = <Safety.NOOP_ON_UNSAFE: 0>
WARN_ON_UNSAFE = <Safety.WARN_ON_UNSAFE: 1>
ERROR_ON_UNSAFE = <Safety.ERROR_ON_UNSAFE: 2>
class Select(enum.Enum):

Enumeration for specifying items to select

  • NONE: Set all items to unselected
  • ALL: Set all items to selected
  • INVERT: Set all items to the inverse of their currently selected state
NONE = <Select.NONE: 0>
ALL = <Select.ALL: 1>
INVERT = <Select.INVERT: 2>
class SelectionState(enum.Enum):

Enumeration for specifying selection durability

  • TRANSIENT: Selection is cleared after next operation
  • DURABLE: Selection persists until explicitly modified
TRANSIENT = <SelectionState.TRANSIENT: 0>
DURABLE = <SelectionState.DURABLE: 1>
class StoreRule(enum.Enum):

An enumeration.

DELETE_INSERT = <StoreRule.DELETE_INSERT: 1>
DO_NOT_REPLACE = <StoreRule.DO_NOT_REPLACE: 2>
REPLACE_ALL = <StoreRule.REPLACE_ALL: 3>
REPLACE_MISSING_VALUES_ONLY = <StoreRule.REPLACE_MISSING_VALUES_ONLY: 4>
REPLACE_WITH_NON_MISSING = <StoreRule.REPLACE_WITH_NON_MISSING: 5>
class TimeSeries:

Holds time series and provides time series operations.

Structure

TimeSeries objects contain the following properties

  • watershed (Optional): A string that holds the the DSS A pathname part. Unused in CWMS contexts.
  • location (Required): A Location object. Its name property is used for the CWMS location identifier or DSS B pathname part.
  • parameter (Required): A Parameter object. May be an ElevParameter if the base parameter is "Elev", but only if there is vertical datum info. Its name property is used for the CWMS parameter identifier or DSS C pathname part.
  • parameter_type (Optional): A ParameterType object. Its name property is used for the CWMS parameter type identifier or DSS data type
  • interval (Required): An Interval object. Its name property is used for the CWMS interval identier or DSS E pathname poart
  • duration (Optional): A Duration object. Its name property is used for the CWMS duration identifier. Unused in DSS contexts.
  • version (Optional): A string that holds the CWMS version identifier or DSS F pathname part.
  • data (Optiona): A pandas.DataFrame object containing the time series data. The DataFrame has a DateTime index, a float column named "value" and a integer column named "quality"

Other properties

  • name: The name used to initalize the object. Will be a valid CWMS time series identifier or DSS time series pathname.
  • unit: The unit of the parameter. Also available as the unit_name property of the parameter proerty.
  • time_zone: The time zone of the data or None if not set
  • vertical_datum_info_xml: The vertical datum info as an XML string
  • vertical_datum_info_dict: The vertical datum info as a dictionary
  • times: The times of the data values as a list of strings
  • values: The data values as a list of floats
  • qualities: The quality codes of the data values as a list of integers
  • slice_stop_exclusive: Controls slicing behavior

Indexing and slicing

In addition to operations available on the data DataFrame, TimeSeries objects may also be indexed by individual indexes or slices.

The result of an index or slice operation is a copy TimeSeries object with the data as indicated in the index or slice.

Indexes (single, as well as start and stop values for slices) may be one of:

  • HecTime object
  • datetime object
  • String - must be in the format yyyy‑mm‑dd hh:mm:ss([+|‑]hh:mm). The time zone portion is required if the data times have the time zone specified
  • Integer (index into the list of data times using normal python indexing)

Slice steps are supported and must be a positive integer value (times must always increase)

By default, slicing follows python behavior where the stop value is exclusive (not included in the returned data). To use DataFrame behavior where the stop value is inclusive (returned in the data):

  • call TimeSeries.set_slice_stop_inclusive() before creating any TimeSeries objects
  • set the slice_stop_exclusive property to False on existing TimeSeries objects.

Note that slicing of the data object will always use DataFrame behavior.

In-Place Methods

All methods that return a time series have an optional parameter named in_place that defaults to False:

  • Leaving unspecified or specifying False will cause the method to return a new time series, leaving the time series on which the method is called unchanged and available for future use.
  • Specifying True will modify the time series on which the method is called and return the modified time series. The return value may of course be ignored if desired.

Each of these method also has a "in-place" method without the in_place parameter and which simply calls the original method with in_place=True. The methods are named the same as the original methods prepended with the letter 'i' (e.g., select() --> iselect(), set_parameter() --> iset_parameter())

TimeSeries( name: str, times: Union[list[Union[HecTime, datetime.datetime, str]], pandas.core.indexes.datetimes.DatetimeIndex, NoneType] = None, values: Union[list[float], float, NoneType] = None, qualities: Union[list[Union[Quality, int]], Quality, int, NoneType] = None, time_zone: Optional[str] = None)

Initializes a new TimeSeries object. To generate a new regular interval time series using start time, end time, interval, and offset see also new_regular_time_series()

Arguments:
  • name (str): The time series name. Must be either a CWMS time series identifier or HEC-DSS time series pathname.
    • If CWMS
      • The following components are set from the identifier:
        • location (may be in the format <office>/<location> to set office)
        • parameter
        • parameter type
        • interval
        • duration
        • version
      • The following components are not set:
        • watershed
    • If HEC-DSS
      • The following components are set from the pathname:
        • A => watershed
        • B => location
        • C => parameter
        • E => interval
        • F => version
      • The following components are set by default:
        • parameter type:
          • INST_CUM if C includes "Precip" (case insensitive)
          • INST_VAL otherwise
      • The following compents are not set:
        • duration
    • The parameter unit is set to the default English unit
    • No vertical datum information is set for elevation parameter
  • times (Optional[Union[list[Union[HecTime, datetime, str]], pd.DatetimeIndex]]): The times for the time series. If specified, all times must have the same time zone or no time zone. If not specified, values, qualities, and time_zone my not be specified. Defaults to None.
  • values (Optional[Union[list[float], float]]): A value or a list of values to assign to the specified times. If a single value or a list of values shorter than the list of times, the specified value(s) is/are repeated until each time has an assigned value. Must be specified if times is specified. Defaults to None.
  • qualities (Optional[Union[list[Union[Quality, int]], Quality, int]]): A quality code or object or a list of quality codes or objects to assign to the specified times. If a single quality or a list of qualities shorter than the list of times, the specified quality(ies) is/are repeated until each time has an assigned quality. If not specified and times is specified, each time will be assigned a quality code of zeor.Defaults to None.
  • time_zone (Optional[str]): The time zone of the time series. If specified, must be a valid time zone name or "local". Interaction with the time zone of the times argument is as follows. Defaults to None.

    times has time zonetime_zone specifiedTime series time zone
    FalseFalselocal time zone
    FalseTrueas specified in time_zone
    TrueFalseas specified in times
    TrueTrueas specified in time_zone
    times are converted to time_zone
name: str

The CWMS time series identifier or HEC-DSS pathname

Operations:

Read/Write

def accum(self, in_place: bool = False) -> TimeSeries:

Returns a time series whose values are the accumulation of values in this time series.

Missing values are ignored; the accumulation at those times is the same as for the previous time.

If a selection is present, all non-selected items are set to missing before the accumulation is computed. They remain missing in the retuned time series.

Restrictions

  • May be performed only on time series with accumulatable base parameters. Use Parameter.accumulatable_base_parameters() to list the accumulatable base parameters.
  • May be performed only on Instantaneous, Average, or Total time series (CWMS: Inst, Ave, Total, DSS: INST-VAL, INST-CUM, PER-CUM)

See base_parameter_definitions for information on base parameters and their conversions.

Arguments:
  • in_place (bool, optional): If True, this object is modified and retured, otherwise a copy of this object is modified and returned.. Defaults to False.
Raises:
  • TimeSeriesException: If the time series has no data or one of the restrictions listed above is violated.
Returns:

TimeSeries: The accumulation time series

def aggregate( self, func: Union[list[Union[Callable[[Any], Any], str]], Callable[[Any], Any], str]) -> Any:

Perform an aggregation of the values in a time series time series.

Arguments:
  • func (Union[list[Union[Callable[[Any], Any], str]],Callable[[Any], Any], str]): The aggregation function(s).
  • May be one of:

    • list[Union[Callable[[Any], Any], str]]: A list comprised of items from the following two options (note that there is overlap between the python builtin functions and the pandas functions)
    • Callable[[Any], Any]: Must take an iterable of floats and return a float timeseries
      May be a function defined in the code (including lambda funtions) or a standard python aggregation function:

      • all
      • any
      • len
      • max
      • min
      • sum
      • math.prod
      • statistics.fmean
      • statistics.geometric_mean
      • statistics.harmonic_mean
      • statistics.mean
      • statistics.median
      • statistics.median_grouped
      • statistics.median_high
      • statistics.median_low
      • statistics.mode
      • statistics.multimode
      • statistics.pstdev
      • statistics.pvariance
      • statistics.quantiles
      • statistics.stdev
      • statistics.variance

    • str: Must be the name of a pandas aggregation function:

      • "all"
      • "any"
      • "count"
      • "describe"
      • "first"
      • "last"
      • "max"
      • "mean"
      • "median"
      • "min"
      • "nunique"
      • "prod"
      • "sem"
      • "size"
      • "skew"
      • "std"
      • "sum"
      • "var"

Raises:

  • TimeSeriesException: If the time series has no data, or if there are less than two items
  • to aggregate over.
Returns:

The result of the aggregation function(s)

@staticmethod
def aggregate_ts( func: Union[list[Union[Callable[[Any], Any], str]], Callable[[Any], Any], str], timeseries: list[TimeSeries]) -> TimeSeries:

Generate a time series that is an aggregation of multiple time series.

Note that some usages (marked with 1, 2, 3, or 4) generate non-standard TimeSeries results. In these cases the .data property of the TimeSeries should be used directly instead of using the .values property or using the TimeSeries in further operations.

Arguments:
  • func (Union[list[Union[Callable[[Any], Any], str]], Callable[[Any], Any], str]): The aggregation function(s).
  • May be one of:

    • list[Union[Callable[[Any], Any], str]]1: A list comprised of items from the following two options (note that there is overlap between the python builtin functions and the pandas functions)
    • Callable[[Any], Any]: Must take an iterable of floats and return a single value
      May be a function defined in the code (including lambda funtions) or a standard python aggregation function:

      • all2
      • any2
      • len
      • max
      • min
      • sum
      • math.prod
      • statistics.fmean
      • statistics.geometric_mean
      • statistics.harmonic_mean
      • statistics.mean
      • statistics.median
      • statistics.median_grouped
      • statistics.median_high
      • statistics.median_low
      • statistics.mode
      • statistics.multimode3
      • statistics.pstdev
      • statistics.pvariance
      • statistics.quantiles3
      • statistics.stdev
      • statistics.variance

    • str: Must be the name of a pandas aggregation function:

      • "all"2
      • "any"2
      • "count"
      • "describe"1
      • "first"
      • "last"
      • "max"
      • "mean"
      • "median"
      • "min"
      • "nunique"
      • "prod"
      • "sem"
      • "size"4
      • "skew"
      • "std"
      • "sum"
      • "var"

  • timeseries (list[TimeSeries]): The time series for the function to aggregate over
1The `.data` property is a DataFrame with named columns.
2The "Values" column of the `.data` property contains bool values float values
3The "Values" column of the `.data` property contains lists of values instead of float values.
4The `.data` property is a DataFrame with one unnamed column.
Raises:

  • TimeSeriesException: If less than two of the time series have data, or if the time series have no common times.
Returns:

TimeSeries: The time series that is the result of the aggregation function. The times series name will be modified from the first time series specified in the following way:


  • The parameter will be "Code"
  • the version will be "Aggregate"

can_determine_unit_system: bool

Returns whether the unit of this time series is recognized as an English unit, or a Metric unit, but not both

Operations:

Read Only

def centered_moving_average( self, window: int, only_valid: bool, use_reduced: bool, in_place: bool = False) -> TimeSeries:

Computes and returns a time series that is the centered moving average of this time series.

A centered moving average sets the value at each time to be the average of the values at that time and a number of previous and following consecutive times.

Arguments:
  • window (int): The number of values to average over. The result at each time will be the average of the values at ((window-1)/2) previous times, the value at the current time, and the values at ((window-1)/2) following times. The span between times is not accounted for so discretion should be used if the time series is irregular. Must be an odd number.
  • only_valid (bool): Specifies whether to only average over windows where every value is valid. If False, the average at any given time may be computed using fewer values that specified in the window parameter.
  • use_reduced (bool): Specifies whether to allow averages using less than window number of values will be computed at the beginning and end of the times series. If False, the values at the first and last ((window-1)/2) times will be set to missing.
  • in_place (bool, optional): If True, this time series is modified and returned. Otherwise this time series is not modified. Defaults to False.
Raises:
  • TimeSeriesException: If the time series has no data or if the window is invalid.
Returns:

TimeSeries: The averaged time series

def copy(self, include_data: bool = True) -> TimeSeries:

Creates a copy of this object, with or without data

Arguments:
  • include_data (bool, optional): Specifies whether to include the data in the copy. Defaults to True.
Returns:

TimeSeries: The copy of this object

def collapse(self, in_place: bool = False) -> TimeSeries:

Collapses a regular time series (either this one or a copy of this one), removing all missing values unless they are either protected or marked as part of the current selection.

Irregular time series (including pseudo-regular time series) are not affected.

Does not alter any selection, even if selection state is SelectionState.TRANSIENT. Selected items remain selected after collapse even though their location in the data may change.

Arguments:
  • in_place (bool, optional): Specifies whether to collapse this time series (True) or a copy of this time series (False).
  • Defaults to False.
Returns:

TimeSeries: The collapsed time series

context: Optional[str]

The context of the time series. Valid contexts are "CWMS" and "DSS"

Operations:

Read/Write

def convert_to_time_zone( self, time_zone: Union[HecTime, datetime.datetime, zoneinfo.ZoneInfo, str], on_tz_not_set: int = 1, in_place: bool = False) -> TimeSeries:

Converts a time series (either this one or a copy of it) to the spcified time zone and returns it

Arguments:
  • time_zone (Union[HecTime, datetime, ZoneInfo, str]): The target time zone or object containg the target time zone. Use "local" to specify the system time zone.
  • on_tz_not_set (int, optional): Specifies behavior if this object has no time zone attached. Defaults to 1.
    • 0: Quietly behave as if this object had the local time zone attached.
    • 1: (default) Same as 0, but issue a warning.
    • 2: Raise an exception preventing objectes with out time zones attached from using this method.
  • in_place (bool): Specifies whether to convert this time series (True) or a copy of it (False). Defaults to False
Returns:

TimeSeries: The converted time series

def cyclic_analysis(self, method: str = 'linear') -> list[TimeSeries]:

Generates cyclic analysis statistics on this TimeSeries.

The time series must have an interval of 1Hour, 1Day or 1Month. In all cases the statistics are computed for a 1 year cycle reported as year 2100: * 1Hour: Statistics are computed on 8760 1-hour bins * 1Day: Statistics are computed on 365 1-day bins * 1Month: Statistics are computed on 12 1-month bins

The statistics returned are (in order):

  1. Count of valid values in each bin
  2. Date/time of maximum value in each bin
  3. Date/Time of minimum value in each bin
  4. The average (arithmetic mean) of the values in each bin
  5. The maximum value each bin
  6. The minimum value each bin
  7. The 5th percentile value each bin computed according to the specified method
  8. The 10th percentile value each bin computed according to the specified method
  9. The 25th percentile value each bin computed according to the specified method
  10. The 50th percentile value each bin computed according to the specified method
  11. The 75th percentile value each bin computed according to the specified method
  12. The 90th percentile value each bin computed according to the specified method
  13. The 95th percentile value each bin computed according to the specified method
  14. The standard deviation of the values in each bin

The values for date/time statistics are the year of the min or max value (Java code uses yyyy.mmdd on 1Hour statistics).

The report year is 2100. The Java code report year of 3000 is not used due to current limitations of the pandas.DatetimeIndex type.

Arguments:
  • method (str): The method to use for generating the probability statistics. Must be one of the following. Defaults to 'linear'.
    • 'hecmath': Specifies using the alorithm used in the Java hec.hecmath.TimeSeriesMath.cyclicAnalysis() method, which performs a version of nearest-rank percentile.
    • others: Specify the NumPy method to use for numpy.percentile(). Must be one of
      • 'averaged_inverted_cdf'
      • 'closest_observation'
      • 'hazen'
      • 'higher'
      • 'interpolated_inverted_cdf'
      • 'inverted_cdf'
      • 'linear'
      • 'lower'
      • 'median_unbiased'
      • 'midpoint '
      • 'nearest'
      • 'normal_unbiased'
      • 'weibull'
Raises:
  • TimeSeriesException: if the time series is empty or an invalid method is specified.
Returns:

list[TimeSeries]: The 14 time series containing the cyclic analysis statistics

data: Optional[pandas.core.frame.DataFrame]

The data as a DataFrame or None if not set. Note this exposes the interal DataFrame object to allow direct modification. For uses that should not modify this TimeSeries object, the DataFrame should be copied using its copy() method prior to modification (e.g., df = ts.data.copy())

Operations:

Read Only

def diff(self, in_place: bool = False) -> TimeSeries:

Returns a time series whose values are the differences of successive values in this time series.

A missing value at a specific time in the source time series will cause the value at that and the next time in the result time sereies to be missing.

If a selection is present, all non-selected items are set to missing before the accumulation is computed. They remain missing in the retuned time series.

Restrictions

  • May be performed only on time series with accumulatable base parameters. Use Parameter.accumulatable_base_parameters() to list the accumulatable base parameters.
  • May be performed only on Instantaneous, Average, or Total time series (CWMS: Inst, Ave, Total, DSS: INST-VAL, INST-CUM, PER-CUM)

See base_parameter_definitions for information on base parameters and their conversions.

Arguments:
  • in_place (bool, optional): If True, this object is modified and retured, otherwise a copy of this object is modified and returned.. Defaults to False.
Raises:
  • TimeSeriesException: If the time series has no data.
Returns:

TimeSeries: The time series of differences

duration: Optional[Duration]

The duration object

Operations:

Read Only

def estimate_missing_values( self, max_missing_count: int, accumulation: bool = False, estimate_rejected: bool = True, set_questioned: bool = True, in_place: bool = False) -> TimeSeries:

Estimates missing values in a time series using specified criteria, and returns the estimated time series (either this time series or a copy of it). Values are estimated using linear interpolation between the bounding valid values

Arguments:
  • max_missing_count (int): The maximum number of consecutive missing values that will be replaced with estimates. Groups of consecutive missing values larger than this number remain missing (except see accumulation).
  • accumulation (bool, optional): Specifies whether the time series is an accumulation (e.g., cumulative precipitaion). The estimation behavior for accumulation time series differs in that
    • If the bounding valid values for a group of consecutive missing values decrease with increasing time, no estimations are performed
    • If the bounding valid values for a group of consecutive missing values are equal, the all missing values in the group are replaced with the same value, without regard to max_missing_count Defaults to False.
  • estimate_rejected (bool, optional): Specifies whether to treat values in the time series with Rejected quality as missing. Defaults to True.
  • set_questioned (bool, optional): Specifies whether to set the quality for estimated values to Questionable. If False, quality is set to Okay. Defaults to True.
  • in_place (bool, optional): Specfies whether to modify and return this time series (True) or a copy of this time series (False). Defaults to False.
Raises:
  • TimeSeriesException: If there are no values in the time series
Returns:

TimeSeries: The estimated time series

def expand( self, start_time: Union[str, datetime.datetime, HecTime, NoneType] = None, end_time: Union[str, datetime.datetime, HecTime, NoneType] = None, in_place: bool = False) -> TimeSeries:

Expands a regular time series (either this one or a copy of this one) so that there are no gaps in time (fills gaps with missing values) and returns the expanded time series. If start_time and/or end_time are specified, the times between the start_time and the first time and between the last time and the end_time are considered as gaps to be filled.

Irregular time series (including pseudo-regular time series) are not affected.

Does not alter any selection, even if selection state is SelectionState.TRANSIENT. Selected items remain selected after expansion even though their location in the data may change.

Arguments:
  • start_time (Optional[Union[str, datetime, HecTime]]): The beginning of the timespan before the first time to fill with missing values. Does not need to fall on the time series interval. If not at least one full interval prior to the first time, no missing values will be inserted before the first time. Defaults to None.
  • end_time (Optional[Union[str, datetime, HecTime]]): The end of the timespan after the last time to fill with missing values. Does not need to fall on the time series interval. If not at least one full interval after the last time, no missing values will be inserted after the last time. Defaults to None.
  • in_place (bool, optional): Specifies whether to expand this time series (True) or a copy of this time series (False).
  • Defaults to False.
Returns:

TimeSeries: The expanded time series

def filter( self, unselected: bool = False, in_place: bool = False) -> TimeSeries:

Filters a time series (either this one or a copy of this one) and returns the results. The returned time series will contain only the selected or unselected items in the original time series.

Arguments:
  • unselected (bool, optional): Specifies including only selected itmes (False) or only unselected items (True). Defaults to False.
  • in_place (bool, optional): Specifies whether to modifiy this time series (True) or a copy of it (False). Defaults to False.
Returns:

TimeSeries: The filtered time series

def ifilter(self, unselected: bool = False) -> TimeSeries:

Convenience method for executing fileter(...) with in_place=True.

first_valid_time: Optional[numpy.datetime64]

The time of the first valid value in the time series. Values are valid unless any of the following are true:

  • The quality is MISSING
  • The quality is REJECTED
  • The value is NaN
  • The value is Infinite
Operations:

Read Only

first_valid_value: Optional[float]

The first valid value in the time series. Values are valid unless any of the following are true:

  • The quality is MISSING
  • The quality is REJECTED
  • The value is NaN
  • The value is Infinite
Operations:

Read Only

def fmod( self, amount: Union[TimeSeries, UnitQuantity, float, int], in_place: bool = False) -> TimeSeries:

Returns the result of fmod() of the values of this time series with either a constant or another time series.

Arguments:
  • amount (Union[TimeSeries, UnitQuantity, float, int]): The constant or time series to use in the operation
  • in_place (bool, optional): Whether to modify and return this time series. Defaults to False.
Returns:

TimeSeries: the resulting time series

def format_time_for_index(self, item: Union[HecTime, datetime.datetime, str]) -> str:

Formats a time item for indexing into the times of this object. The formatting depends on the setting of this object's mindnight_as_2400 property

Arguments:
  • item (Union[HecTime, datetime, str]): The time item to format.
Returns:

str: The formatted string with the midnight setting of this object

def forward_moving_average( self, window: int, only_valid: bool, use_reduced: bool, in_place: bool = False) -> TimeSeries:

Computes and returns a time series that is the forward moving average of this time series.

A forward moving average sets the value at each time to be the average of the values at that time and a number of previous consecutive times.

Arguments:
  • window (int): The number of values to average over. The result at each time will be the average of the values at (window-1) previous times and the value at the current time. The span between times is not accounted for so discretion should be used if the time series is irregular.
  • only_valid (bool): Specifies whether to only average over windows where every value is valid. If False, the average at any given time may be computed using fewer values that specified in the window parameter.
  • use_reduced (bool): Specifies whether to allow averages using less than window number of values will be computed at the beginning of the times series. If False, the values at the first (window-1) times will be set to missing.
  • in_place (bool, optional): If True, this time series is modified and returned. Otherwise this time series is not modified. Defaults to False.
Raises:
  • TimeSeriesException: If the time series has no data or if the window is invalid.
Returns:

TimeSeries: The averaged time series

@staticmethod
def from_native(datastore: Any, native_ts: Any) -> TimeSeries:

Returns a TimeSeries object generated from native format of the specified data store.

Arguments:
  • datastore (Any): The datastore that specifies the native format
    • If an instance of CwmsDataStore, native_ts must be a cwms.cwms_types.Data object suitable for use with the cwms-python package
    • If an instance of DssDataStore, native_ts must be an hecdss.RegularTimeSeries or hecdss.IrregularTimeSeries object suitable for use wth the hecdss package
  • native_ts (Any): The native-format time series. Much match the format of the specified data store
Returns:

TimeSeries: The generated TimeSeries object

def get_differentiation_parameter(self) -> Parameter:

Returns a new Parameter object appropriate for differentiating this time series with respect to time.

The new parameter will preserve any sub-parameter of this time series as well as the unit system of this time sereis.

Raises:
Returns:

Parameter: The new parameter object

def get_integration_parameter(self) -> Parameter:

Returns a new Parameter object appropriate for integrating this time series over time.

The new parameter will preserve any sub-parameter of this time series as well as the unit system of this time sereis.

Raises:
Returns:

Parameter: The new parameter object

def has_same_times(self, other: TimeSeries) -> bool:

Returns whether another time series has the same times as this time series.

Arguments:
  • other (TimeSeries): The other time series
Returns:

bool: Whether another time series has the same times as this time series.

has_selection: bool

Whether the object has a current selection specified

Operations:

Read Only

def iaccum(self) -> TimeSeries:

Convenience method for executing accum(...) with in_place=True.

def icentered_moving_average( self, window: int, only_valid: bool, use_reduced: bool, in_place: bool = False) -> TimeSeries:

Convenience method for executing centered_moving_average(...) with in_place=True.

def icollapse(self) -> TimeSeries:

Convenience method for executing collapse(...) with in_place=True.

def iconvert_to_time_zone( self, time_zone: Union[HecTime, datetime.datetime, zoneinfo.ZoneInfo, str], on_tz_not_set: int = 1) -> TimeSeries:

Convenience method for executing convert_to_time_zone(...) with in_place=True.

def idiff(self, in_place: bool = False) -> TimeSeries:

Convenience method for executing diff(...) with in_place=True.

def iestimate_missing_values( self, max_missing_count: int, accumulation: bool = False, estimate_rejected: bool = True, set_questioned: bool = True) -> TimeSeries:

Convenience method for executing estimate_missing_values(...) with in_place=True.

def iexpand( self, start_time: Union[str, datetime.datetime, HecTime, NoneType] = None, end_time: Union[str, datetime.datetime, HecTime, NoneType] = None) -> TimeSeries:

Convenience method for executing expand(...) with in_place=True.

def iforward_moving_average( self, window: int, only_valid: bool, use_reduced: bool, in_place: bool = False) -> TimeSeries:

Convenience method for executing forward_moving_average(...) with in_place=True.

def ifmod( self, amount: Union[TimeSeries, UnitQuantity, float, int]) -> TimeSeries:

Convenience method for executing fmod(...) with in_place=True.

def imap(self, func: Callable[[float], float]) -> TimeSeries:

Convenience method for executing map(...) with in_place=True.

def ilabel_as_time_zone( self, time_zone: Union[HecTime, datetime.datetime, zoneinfo.ZoneInfo, str, NoneType], on_already_set: int = 1) -> TimeSeries:

Convenience method for executing label_as_time_zone(...) with in_place=True.

def imerge( self, other: Union[TimeSeries, List[TimeSeries]]) -> TimeSeries:

Convenience method for executing merge(...) with in_place=True.

def index_of( self, item_to_index: Union[HecTime, datetime.datetime, int, str], not_found: Optional[str] = None) -> str:

Retrieves the data index of a specified object

Arguments:
  • item_to_index (Union[HecTime, datetime, int, str]): The object to retrieve the index of.
    • HecTime: an HecTime object
    • datetime: a datetime object
    • int: a normal python index
    • str: a date-time string
  • not_found (Optional[str]): Specifies the behavior if item_to_index is not in the index:
    • 'next': return the higher of the bounding indices of the item
    • 'previous': return the lower of the bounding indices of the item
    • 'stop': used for the stop index of slices - return the lower of the bounding indices plus one (unless beyond end)
    • None (default): raise an IndexError
Raises:
  • TimeSeriesException: If the time series has no values, or if not_found is specifed and is not "next" "previous", or "stop"
  • TypeError: If item_to_index is not one of the expected types
  • IndexError: * int: If the integer is out of range of the number of times
    • Others: If no index item matches the input object
Returns:

str: The actual index item that for the specified object

interval: Interval

The interval object (used in HEC-DSS E pathname part)

Operations:

Read Only

def iolympic_moving_average( self, window: int, only_valid: bool, use_reduced: bool, in_place: bool = False) -> TimeSeries:

Convenience method for executing olympic_moving_average(...) with in_place=True.

def iresample( self, operation: str, interval: Union[TimeSeries, TimeSpan, datetime.timedelta, NoneType] = None, offset: Union[int, TimeSpan, datetime.timedelta, NoneType] = None, start_time: Union[str, datetime.datetime, HecTime, NoneType] = None, end_time: Union[str, datetime.datetime, HecTime, NoneType] = None, max_missing_percent: float = 25.0, entire_interval: Optional[bool] = None, before: Union[str, float] = 0.0, after: Union[str, float] = 'LAST') -> TimeSeries:

Convenience method for executing resample(...) with in_place=True.

def iround_off(self, precision: int, tens_place: int) -> TimeSeries:

Convenience method for executing round_off(...) with in_place=True.

is_any_irregular: bool

Specifies whether the time series is a normal irregular or pseudo-regular time series

Operations:

Read Only

is_any_regular: bool

Specifies whether the time series is a normal regular or local regular time series

Operations:

Read Only

@staticmethod
def is_cwms_ts_id(identifier: str) -> bool:

Returns whether the specified identifier is a valid CWMS time series identifier

Arguments:
  • identifier (str): The identifier
Returns:

bool: Whether the identifier is a valid CWMS time series identifier

@staticmethod
def is_dss_ts_pathname(identifier: str) -> bool:

Returns whether the specified identifier is a valid HEC-DSS time series pathname

Arguments:
  • identifier (str): The identifier
Returns:

bool: Whether the identifier is a valid HEC-DSS time series pathname

is_english: bool

Returns whether the unit of this time series is recognized as an English unit

Operations:

Read Only

is_irregular: bool

Specifies whether the time series is a normal irregular time series

Operations:

Read Only

is_local_regular: bool

Specifies whether the time series is a local regular time series

Operations:

Read Only

is_metric: bool

Returns whether the unit of this time series is recognized as an Metric unit

Operations:

Read Only

is_pseudo_regular: bool

Specifies whether the time series is a normal irregular or pseudo-regular time series

Operations:

Read Only

is_regular: bool

Specifies whether the time series is a normal regular time series

Operations:

Read Only

def is_valid( self, index: Union[int, str, datetime.datetime, HecTime]) -> bool:

Returns whether the index is in the time series and the value at the index is valid

Arguments:
  • index (Union[int, str, datetime, HecTime]): The index to test.
Returns:

bool: False if any of the following are true, otherwise True:

  • The time series does not contain the index
  • The quality is MISSING
  • The quality is REJECTED
  • The value is NaN
  • The value is Infinite
def iscreen_with_constant_value( self, duration: Union[Duration, str], missing_limit: float = nan, reject_limit: float = nan, question_limit: float = nan, min_threshold: float = nan, percent_valid_required: float = nan) -> TimeSeries:

Convenience method for executing screen_with_constant_value(...) with in_place=True.

def iscreen_with_duration_magnitude( self, duration: Union[Duration, str], min_missing_limit: float, min_reject_limit: float, min_question_limit: float, max_question_limit: float, max_reject_limit: float, max_missing_limit: float, percent_valid_required: float = 0.0) -> TimeSeries:

Convenience method for executing screen_with_duration_magnitude(...) with in_place=True.

def iscreen_with_forward_moving_average( self, window: int, only_valid: bool, use_reduced: bool, diff_limit: float, invalid_validity: str = 'M') -> TimeSeries:

Convenience method for executing screen_with_forward_moving_average(...) with in_place=True.

def iscreen_with_value_change_rate( self, min_reject_limit: float = nan, min_question_limit: float = nan, max_question_limit: float = nan, max_reject_limit: float = nan) -> TimeSeries:

Convenience method for executing screen_with_value_change_rate(...) with in_place=True.

def iscreen_with_value_range( self, min_reject_limit: float = nan, min_question_limit: float = nan, max_question_limit: float = nan, max_reject_limit: float = nan) -> TimeSeries:

Convenience method for executing screen_with_value_range(...) with in_place=True.

def iscreen_with_value_range_or_change( self, min_limit: float = nan, max_limit: float = nan, change_limit: float = nan, replace_invalid_value: bool = True, invalid_value_replacement: float = nan, invalid_validity: str = 'M') -> TimeSeries:

Convenience method for executing screen_with_value_range_or_change(...) with in_place=True.

def iselect( self, selection: Union[Select, int, slice, Callable[[TimeSeriesValue], bool]], combination: Combine = <Combine.REPLACE: 1>) -> TimeSeries:

Convenience method for executing select(...) with in_place=True.

def iselect_valid(self) -> TimeSeries:

Convenience method for executing select_valid(...) with in_place=True.

def iset_duration( self, value: Union[Duration, str, int]) -> TimeSeries:

Convenience method for executing set_duration(...) with in_place=True.

def iset_interval( self, value: Union[Interval, str, int]) -> TimeSeries:

Convenience method for executing set_interval(...) with in_place=True.

def iset_location( self, value: Union[Location, str]) -> TimeSeries:

Convenience method for executing set_location(...) with in_place=True.

def iset_parameter( self, value: Union[Parameter, str]) -> TimeSeries:

Convenience method for executing set_parameter(...) with in_place=True.

def iset_parameter_type( self, value: Union[ParameterType, str]) -> TimeSeries:

Convenience method for executing set_parameter_type(...) with in_place=True.

def iset_protected(self) -> TimeSeries:

Convenience method for executing set_protected(...) with in_place=True.

def iset_quality( self, quality: Union[Quality, int]) -> TimeSeries:

Convenience method for executing set_quality(...) with in_place=True.

def iset_unit(self, value: Union[pint.registry.Unit, str]) -> TimeSeries:

Convenience method for executing set_unit(...) with in_place=True.

def iset_unprotected(self) -> TimeSeries:

Convenience method for executing set_unprotected(...) with in_place=True.

def iset_value(self, value: float) -> TimeSeries:

Convenience method for executing set_value(...) with in_place=True.

def iset_value_quality( self, value: float, quality: Union[Quality, int]) -> TimeSeries:

Convenience method for executing set_value_quality(...) with in_place=True.

def iset_vertical_datum_info(self, value: Union[str, dict[str, Any]]) -> TimeSeries:

Convenience method for executing set_vertical_datum_info(...) with in_place=True.

def isnap_to_regular( self, interval: Union[Interval, str], offset: Union[TimeSpan, datetime.timedelta, str, NoneType] = None, backward: Union[TimeSpan, datetime.timedelta, str, NoneType] = None, forward: Union[TimeSpan, datetime.timedelta, str, NoneType] = None) -> TimeSeries:

Convenience method for executing snap_to_regular(...) with in_place=True.

def itime_derivative(self, in_place: bool = False) -> TimeSeries:

Convenience method for executing time_derivative(...) with in_place=True.

def ito( self, unit_parameter_or_datum: Union[str, pint.registry.Unit, Parameter]) -> TimeSeries:

Convenience method for executing to(...) with in_place=True.

def ito_irregular( self, interval: Union[Interval, str]) -> TimeSeries:

Convenience method for executing to_irregular(...) with in_place=True.

def itrim(self) -> TimeSeries:

Convenience method for executing trim(...) with in_place=True.

def kurtosis(self) -> float:

Computes the kurtosis coefficient of the values in the time series

Raises:
  • TimeSeriesException: If the time series has no data or fewer than 2 items selected.
Returns:

float: The kurtosis coefficient

def label_as_time_zone( self, time_zone: Union[HecTime, datetime.datetime, zoneinfo.ZoneInfo, str, NoneType], on_already_set: int = 1, in_place: bool = True) -> TimeSeries:

Attaches the specified time zone to this object or a copy of this object and returns it. Does not change the actual times

Arguments:
  • time_zone (Optional[Union["HecTime", datetime, ZoneInfo, str]]): The time zone to attach or object containing that time zone.
    • Use "local" to specify the system time zone.
    • Use None to remove time zone information
  • on_already_set (int): Specifies action to take if a different time zone is already attached. Defaults to 1.
    • 0: Quietly attach the new time zone
    • 1: (default) Issue a warning about attaching a different time zone
    • 2: Raises an exception
  • in_place (bool): Specifies whether to attach the time zone to this time series (True) or a copy of it (False). Defaults to False
Raises:
  • TimeSeriesException: if a different time zone is already attached and on_already_set == 2
Returns:

TimeSeries: The modified object

last_valid_time: Optional[numpy.datetime64]

The time of the last valid value in the time series. Values are valid unless any of the following are true:

  • The quality is MISSING
  • The quality is REJECTED
  • The value is NaN
  • The value is Infinite
Operations:

Read Only

last_valid_value: Optional[float]

The last valid value in the time series. Values are valid unless any of the following are true:

  • The quality is MISSING
  • The quality is REJECTED
  • The value is NaN
  • The value is Infinite
Operations:

Read Only

location: Location

The location object (used in HEC-DSS B pathname part)

Operations:

Read Only

def map( self, func: Callable[[float], float], in_place: bool = False) -> TimeSeries:

Applies a function of one variable to the values of this object and returns the modified object

Arguments:
  • func (Callable): The function of one variable to apply to the values
  • in_place (bool, optional): Specifies whether to operate on this object (True) or a copy of this object (False). Defaults to False.
Returns:

TimeSeries: Either this object (modified) or a modified copy of this object.

def max_value(self) -> float:

Returns the maximum value in the time series.

Raises:
  • TimeSeriesException: If the time series has no data
Returns:

float: The maximum value in the time series

def max_value_time(self) -> HecTime:

Returns the time of maximum value in the time series.

Raises:
  • TimeSeriesException: If the time series has no data
Returns:

float: The time of maximum value in the time series. If the maximum value occurs more than once, the earliest time is returned.

def merge( self, other: Union[TimeSeries, List[TimeSeries]], in_place: bool = False) -> TimeSeries:

Merges one or more time series into either this time series or a copy of it, and returns the merged time series.

When the same time exists while merging, the following precedence is followed:

  • other protected value (incoming protected trumps existing protected)
  • this protected value
  • this unprotected value if it is not NaN or infinite
  • other unprotected value if it is not NaN or infinte
Arguments:
  • other (Union["TimeSeries", List["TimeSeries"]]): The other times series (one or a list) to merge. If a list, each other time series is merged in sequence, with earlier results acting as this time series for later merges
  • in_place (bool, optional): Specifies whether to merge into this time series (True) or a copy of it (False). Defaults to False.
Raises:
  • TimeSeriesException: If this time series is a regular time series and the merged times are not all on the interval
Returns:

TimeSeries: The merged time series

midnight_as_2400: bool

The object's current setting of whether to show midnight as hour 24 (default) or not.

Operations:

Read/Write

def min_value(self) -> float:

Returns the minimum value in the time series.

Raises:
  • TimeSeriesException: If the time series has no data
Returns:

float: The minimum value in the time series

def min_value_time(self) -> HecTime:

Returns the time of minimum value in the time series.

Raises:
  • TimeSeriesException: If the time series has no data
Returns:

float: The time of minimum value in the time series. If the minimum value occurs more than once, the earliest time is returned.

@staticmethod
def new_regular_time_series( name: str, start: Union[HecTime, datetime.datetime, str], end: Union[HecTime, datetime.datetime, str, int], interval: Union[Interval, datetime.timedelta, str], offset: Union[TimeSpan, datetime.timedelta, str, int, NoneType] = None, time_zone: Optional[str] = None, values: Union[List[float], float, NoneType] = None, qualities: Union[list[Union[Quality, int]], Quality, int, NoneType] = None) -> TimeSeries:

Generates and returns a new regular (possibly local regular) interval time series with the specified times, values, and qualities.

Arguments:
  • name (str): The name of the time series. The interval portion will be overwritten by the interval if they don't agree
  • start (Union[HecTime, datetime, str]): The specified start time. The actual start time may be later than this, depending on interval and offset
  • end (Union[HecTime, datetime, str, int]): Either the specified end time or, if int, the number of intervals in the time series. The actual end time may be earlier than the specified end time, depending on interval and offset
  • interval (Union[Interval, timedelta, str]): The interval of the time series. Will overwrite the interval portion of name. If it is a local regular interval and start includes a time zone, then the time series will be a local regular time series
  • offset (Optional[Union[TimeSpan, timedelta, str, int]]): The interval offset. If int, then number of minutes. If none, then the offset is determined from start (it's offset into the specified interval). Defaults to None.
  • time_zone (Optional[str]): The time zone. Must be specified if interval is a local-regular interval.
  • values (Optional[Union[List[float], float]]): The value(s) to populate the time series with. If float, it specifies all values. If list, the list is repeated as many whole and/or partial time as necessary to fill the time series. Defaults to None, which causes all values to be NaN.
  • qualities (Optional[Union[list[Union[Quality, int]], Quality, int]]): The qualities to fill the time series with. If Quality or int, it specifies all qualities. If list, the list is repeated as many whole and/or partial times to fill the time sries Defaults to None, which causes all qualities to be zero.
Raises:
Returns:

TimeSeries: The generated regular (possible local regular) interval time series

number_invalid_values: int

The number of invalid values in the time series. Values are invalid if any of the following are true:

  • The quality is MISSING
  • The quality is REJECTED
  • The value is NaN
  • The value is Infinite
Operations:

Read Only

number_missing_values: int

The number of invalid values in the time series. Values are missing if either of the following are true:

  • The quality is MISSING
  • The value is NaN
Operations:

Read Only

number_questioned_values: int

The number of values in the time series that have quality of QUESTIONABLE:

Operations:

Read Only

number_rejected_values: int

The number of values in the time series that have quality of REJECTED:

Operations:

Read Only

number_valid_values: int

The number of valid values in the time series. Values are valid unless any of the following are true:

  • The quality is MISSING
  • The quality is REJECTED
  • The value is NaN
  • The value is Infinite
Operations:

Read Only

number_values: int

The number of values in the time series. Same as len(ts).

Operations:

Read Only

def olympic_moving_average( self, window: int, only_valid: bool, use_reduced: bool, in_place: bool = False) -> TimeSeries:

Computes and returns a time series that is the olympic moving average of this time series.

An olympic moving average sets the value at each time to be the average of the values at that time and a number of previous and following consecutive times, disregarding the minimum and maximum values in the range to average over.

Arguments:
  • window (int): The number of values to average over. The result at each time will be the average of the values at ((window-1)/2) previous times, the value at the current time, and the values at ((window-1)/2) following times, not using the minimum and maximum values in the window. The span between times is not accounted for so discretion should be used if the time series is irregular. Must be an odd number.
  • only_valid (bool): Specifies whether to only average over windows where every value is valid. If False, the average at any given time may be computed using fewer values that specified in the window parameter.
  • use_reduced (bool): Specifies whether to allow averages using less than window number of values will be computed at the beginning and end of the times series. If False, the values at the first and last ((window-1)/2) times will be set to missing.
  • in_place (bool, optional): If True, this time series is modified and returned. Otherwise this time series is not modified. Defaults to False.
Raises:
  • TimeSeriesException: If the time series has no data or if the window is invalid.
Returns:

TimeSeries: The averaged time series

parameter: Parameter

The parameter object (used in HEC-DSS C pathname part)

Operations:

Read Only

parameter_type: Optional[ParameterType]

The parameter type object

Operations:

Read Only

def percentile(self, pct: float) -> float:

Computes the specified percentile of the values in the time series

Arguments:
  • pct (float): The desired percentile in the range of 1..100
Raises:
  • TimeSeriesException: If the time series has no data or fewer than 2 items selected.
Returns:

float: The value for the specified percentile

@staticmethod
def percentile_ts( pct: float, timeseries: list[TimeSeries]) -> TimeSeries:

Computes the specified percentile of the values in the time series

Arguments:
  • pct (Union[tuple[float, ...], list[float], float]): The desired percentile in the range of 1..100 or a list or tuple of such percentiles.
Raises:
  • TimeSeriesException: If the time series has no data or fewer than 2 items selected.
Returns:

TimeSeries: The time series of percentiles for each time. The times series name will be modified from the first time series specified in the following way:

  • The parameter will be "Code-Percentile"
  • the version will be "-percentile" with replaced by the pct parameter with any decimal point replaced with an underscore (_) character
qualities: list[int]

The qualities as a list of integers (empty if there is no data)

Operations:

Read Only

def resample( self, operation: str, interval: Union[TimeSeries, TimeSpan, datetime.timedelta, NoneType] = None, offset: Union[int, TimeSpan, datetime.timedelta, NoneType] = None, start_time: Union[str, datetime.datetime, HecTime, NoneType] = None, end_time: Union[str, datetime.datetime, HecTime, NoneType] = None, max_missing_percent: float = 25.0, entire_interval: Optional[bool] = None, before: Union[str, float] = 0.0, after: Union[str, float] = 'LAST', in_place: bool = False) -> TimeSeries:

Resamples a time series using a specified operation onto an interval or time pattern and returns the result, which may be a new time series or this time series modified.

For this method document:

  • old: pertains to the time series this method is called on
  • new: pertains to the result time series
  • point: a time/value combination in a time series
  • interval: the time between one point (exclusive) and the next (inclusive), regardless of whether it corresponds to an actual Interval
  • interval time: the ending time of the interval

Operation Types

The resample operations are divided in to discreet and continuous operations:

  • Discreet:
    • Count: The number of valid old points in each new interval
    • Maximum: The maximum value of valid old points in each new interval
    • Minimum: The minimum value of valid old points in each new interval
    • Previous: The value of the latest valid old point prior to each new interval time
  • Continuous:
    • Interpolate: Find the value at each new interval time (see callouts in plots below)
    • Integrate: Integrate the time series for each new interval(see shaded area in plots below)
    • Average: The integration of the time series for each new interval divided by the sum of the times used for integration for that interval. Note that this generates the average value in the interval which can be greater than the average value over the interval (integration divided by new interval span) if one or more old points in the new interval are missing or invalid.
    • Accumulate: The accumulation over each new interval (see computations below each plot below). Note that this differs from the accum method which accumulates successive values in a time series.
    • Volume: A special case of Integrate that requires the old time series to have the base parameter of "Flow'; the new base parameter is "Volume"

For discreet operations (except Previous) the entire_interval argument specifies whether to require that each entire old interval falls within the new interval (True) or to allow all old points whose interval time is in the new interval (False).

See base_parameter_definitions for information on base parameters and their conversions.

Parameter Type Effects

Interpolation, which is performed for all continous operations, and accumulation are dependent on the parameter_type of the time series. Each plot below is for a 1-Hour regular time series with the following points:

Time Value
01Feb2025 01:10 1.0
01Feb2025 02:10 2.0
01Feb2025 03:10 3.0
01Feb2025 04:10 4.0
01Feb2025 05:10 3.0
01Feb2025 06:10 2.0

The callouts show the interpolated values at 01:00 (except for Intantaneous), 02:00, 03:00, 04:00, 05:00, and 06:00. The shaded portion show the area used for integration, which is performed not only for the Integrate operation, but Average and Volume operations as well. Below each plot the accumulation from 02:00 to 04:00 is computed.

  • Instantaneous Types (CWMS: Inst, DSS: INST-VAL, INST-CUM): Intantaneous interpolataion and integration
    For instantaeous accumulation (e.g., CWMS: Precip.Inst, DSS INST-CUM), any point with a value lower than the previous point is considered to be invalid, so 05:00 and and 06:00 would be invalid values.
    Accumulation (02:00-04:00) = 3.8333 - 1.8333 = 2.0.
  • Period Constant Types (CWMS: Ave, Const, Min, Max, DSS: PER-AVER, PER-MIN, PER-MAX): Period value interpolataion and integration
    Accumulation (02:00-04:00) = 4.0000 - 2.0000 = 2.0.
  • Period Total Types (CWMS: Total, DSS: PER-CUM): Total interpolataion and integration
    Accumulation (02:00-04:00) = 2.0000 - 1.6667 + 3.0 + 3.3333 = 6.6667.

Parameters, Units, and Parameter Types

The new time series may have different parameter, unit, and/or parameter than the old time series:

  • Count:
    • Parameter: will be "Count-<old_parameter>"
    • Unit: will be "unit"
    • Parameter Type: will be Total (CWMS: Total, DSS: PER-CUM)
  • Maximum
    • Parameter Type: will be Maximum (CWMS: Max, DSS: PER-MAX)
  • Minimum
    • Parameter Type: will be Minimum (CWMS: Min, DSS: PER-MIN)
  • Integrate:
  • Average
    • Parameter Type: will be Average (CWMS: Ave, DSS: PER-AVER)
  • Volume:
    • Parameter: will be "Volume"
    • Unit: will be "ft3" or "m3" depending on the unit system of the old time series

Restrictions

Not all continuous resample operations can be performed on all time series.

  • Integrate:
    • May be performed only on time series with integrable base parameters. Use Parameter.integrable_base_parameters() to list the integrable base parameters.
    • May be performed only on Instantaneous, Average, or constant time series (CWMS: Inst, Ave, Const, DSS: INST-VAL, INST-CUM, PER-AVER)
  • Accumulate:
    • May be performed only on time series with accumulatable base parameters. Use Parameter.accumulatable_base_parameters() to list the accumulatable base parameters.
    • May be performed only on Instantaneous, Average, or Total time series (CWMS: Inst, Ave, Total, DSS: INST-VAL, INST-CUM, PER-CUM)
  • Volume:
    • May be performed only on Instantaneous, Average, or Constant time series (CWMS: Inst, Ave, Const, DSS: INST-VAL, INST-CUM, PER-AVER) with base parameter of "Flow"
Arguments:
  • operation (str): The resample operation to perform. Must be one of Count, Maximum, Minimum, Previous, Interpolate, Integrate, Average, Accumulate, or Volume or a unique beginning portion (case insensitive). 'c' is interpeted as Count, but 'INT' is ambiguous between Interpolate and Integrate.
  • interval (Optional[Union["TimeSeries", TimeSpan, timedelta]]): The interval or time pattern to resample onto. If None, the old interval is used. Otherwise the following can be used:
    • Interval: resample onto a standard regular or local-regular interval
    • TimeSpan or timedelta: resample onto non-standard regular interval
    • TimeSeries: resample onto an irregular time interval Defaults to None.
  • offset (Optional[Union[int, TimeSpan, timedelta]]): Offset into interval for each new time. If specified as an int, the value is in minutes. None is the same as specifying 0, TimeSpan("PT0S"), or timedelta(seconds=0). Defaults to None
  • start_time (Optional[Union[HecTime, datetime, str]]): Start time of the new time series. None specifies the same start time as the old time sereies. Defaults to None.
  • end_time (Optional[Union[HecTime, datetime, str]]): End time of the new time series. None specifies the same end time as the old time sereies. Defaults to None.
  • max_missing_percent (float, optional): The maximum amount of time in each new interval that can be invalid or missing and still perform the resample operation for that interval. If the old time series is regular interval, this is approximately equivalent to the max percent of points that can be invalid or missing. If more than this amount of time is invalid or missing in any new interval, the value for that interval will be set to missing. Defaults to 25.0.
  • entire_interval (Optional[bool]): Used only for discreet resample operations (except Previous). Specifies whether to require each old interval to begin and end in the new interval in order to be considered (True) or to allow all old intervals that end in the new interval (False). If None, each old interval is required toe begin and end in the new interval for all data types except Instantaneous (CWMS: Inst, DSS: INST-VAL, INST-CUM). Defaults to None.
  • before (Union[str, float], optional): Used only for time patterns. Specfies the value for new points (points in the time pattern) that are prior to the beginning of the old time series.
    • float: The floating point value to set the new points to.
    • str: May be one of
      • "FIRST": sets the new values to the first value in the old time series
      • "MISSING": sets the new values to missing Defaults to 0.0.
  • after (Union[str, float], optional): Used only for time patterns. Specfies the value for new points (points in the time pattern) that are after to the end of the old time series.
    • float: The floating point value to set the new points to.
    • str: May be one of
      • "LAST": sets the new values to the last value in the old time series
      • "MISSING": sets the new values to missing Defaults to "LAST".
  • in_place (bool, optional): Specifies whether to resample onto this time series (True) or onto a new time series (False). Defaults to False.
Raises:
  • TimeSeriesException:
    • on time series with no data
    • on time series with no parameter type
    • on invalid operation parameter (matches zero or more than one)
    • on invalid before paremeter
    • on invalid after parameter
    • on empty pattern time series
    • on attempt perform invalid continuous resample operation (see Restrictions) above
  • TypeError:
Returns:

TimeSeries: The resampled time series, whether this one or a new one.

def round_off( self, precision: int, tens_place: int, in_place: bool = False) -> TimeSeries:

Return a time series whose values are rounded according to the parameters.

valueprecisiontens_place>result
123456.78950123460.0
123456.7897-1123456.8
123456.78970123457.0
123456.78971123460.0
Arguments:
  • precision (int): The maximum number of significant digits to use.
  • tens_place (int): The lowest power of 10 to have a non-zero value.
  • in_place (bool, optional): Modify and return this object if True, otherwise modify and return a copy of this object. Defaults to False.
Returns:

TimeSeries: The modified object

def screen_with_constant_value( self, duration: Union[Duration, str], missing_limit: float = nan, reject_limit: float = nan, question_limit: float = nan, min_threshold: float = nan, percent_valid_required: float = nan, in_place: bool = False) -> TimeSeries:

Screens a time series - either this one or a copy of this one - setting values and/or quality codes where the value changes over a specified duration are below specified limits.

Arguments:
  • duration (Union[Duration, str]): The duration over which to screen the value changes. May be a Duration object or the name of a valid duration (e.g., '6Hours', '1Day', ...).
  • missing_limit (float, optional): The mininum value change over the duration that is not flagged as missing. Values flagged as missing also have the value modified to math.nan. Defaults to math.nan (test not performed).
  • reject_limit (float, optional): The mininum non-missing value change over the duration that is not flagged as rejected. Defaults to math.nan (test not performed).
  • question_limit (float, optional): The mininum non-rejected, non-missing value change over the duration that is not flagged as questionable. Defaults to math.nan (test not performed).
  • min_threshold (float, optional): Values less than this will not be screened. Defaults to math.nan (test not performed)
  • percent_valid_required (float, optional): The minimum percent (0..100) of valid values in the duration that will allow the value to be screened. Defaults to math.nan (test not performed). Defaults to math.nan. Values are invalid if any of the following are true:
    • The quality is MISSING
    • The quality is REJECTED
    • The value is NaN
    • The value is Infinite
  • in_place (bool, optional): Specifies whether to modify this time series (True) or a copy of it. Defaults to False.
Raises:
  • TimeSeriesException: If any of the following are true:
    • The time series has fewer than two values to be screened.
    • If percent_valid_required is not in the range 0..100
    • If the non-NaN limits are not in the following increasing-value order:
      • missing_limit
      • reject_limit
      • question_limit
Returns:

TimeSeries: The screened time series

def screen_with_duration_magnitude( self, duration: Union[Duration, str], min_missing_limit: float = nan, min_reject_limit: float = nan, min_question_limit: float = nan, max_question_limit: float = nan, max_reject_limit: float = nan, max_missing_limit: float = nan, percent_valid_required: float = 0.0, in_place: bool = False) -> TimeSeries:

Screens a time series - either this one or a copy of this one - setting values and/or quality codes where the accumulated values over a specified duration are outside the specified range.

Arguments:
  • duration (Union[Duration, str]): The duration over which to screen the accumulated values. May be a Duration object or the name of a valid duration (e.g., '6Hours', '1Day', ...). Accumulations for durations that are not even multiples of regular time series intervals may be used. Irregular time series may also be screened. The end of the duration is always positioned at the time (assumed to be EOP) of the accumulation to be screened. If the beginning of the duration does not align with a data time in the time series, a fraction of the first interval's accumulation is used. Only EOP durations may be used.
  • min_missing_limit (float, optional): The minimum accumulation over the duration that is not flagged as missing. Values flagged as missing also have the value modified to math.nan. Defaults to math.nan (test disabled).
  • min_reject_limit (float, optional): The minimum non-missing accumulation over the duration that is not flagged as rejected. Defaults to math.nan (test disabled).
  • min_question_limit (float, optional): The minimum non-rejected, non-missing accumulation over the duration that is not flagged as questioned. Defaults to math.nan (test disabled).
  • max_question_limit (float, optional): The maximum non-rejected, non-missing accumulation over the duration that is not flagged as questioned. Defaults to math.nan (test disabled).
  • max_reject_limit (float, optional): The maximum non-missing accumulation over the duration that is not flagged as rejected. Defaults to math.nan (test disabled).
  • max_missing_limit (float, optional): The maximum accumulation over the duration that is not flagged as missing. Values flagged as missing also have the value modified to math.nan. Defaults to math.nan (test disabled).
  • percent_valid_required (float, optional): The minimum percent (0..100) of valid values in the accumulation that will allow the value to be screened. Defaults to 0. Values are invalid if any of the following are true:
    • The quality is MISSING
    • The quality is REJECTED
    • The value is NaN
    • The value is Infinite
  • in_place (bool, optional): Specifies whether to modify this time series (True) or a copy of it. Defaults to False.
Raises:
  • TimeSeriesException: If any of the following are true:
    • The time series has fewer than two values to be screened.
    • If percent_valid_required is not in the range 0..100
    • If the non-NaN limits are not in the following increasing-value order:
      • min_missing_limit
      • min_reject_limit
      • min_question_limit
      • max_question_limit
      • max_reject_limit
      • max_missing_limit
Returns:

TimeSeries: The screened time series

def screen_with_forward_moving_average( self, window: int, only_valid: bool, use_reduced: bool, diff_limit: float, failed_validity: str = 'M', in_place: bool = False) -> TimeSeries:

Screens a time series - either this one or a copy of this one - setting values and/or quality codes where the value differ from those of a forward moving averge of the time series by a specified amount.

Arguments:
  • window (int): The number of values to average over. See forward_moving_average() for more info.
  • only_valid (bool): Specifies whether to only average over windows where every value is valid. See forward_moving_average() for more info.
  • use_reduced (bool): Specifies whether to allow averages using less than window number of values will be computed at the beginning of the times series. See forward_moving_average() for more info.
  • diff_limit (float): The maximum difference between a value and the value at the same time in the forward moving average that will not be flagged as questionable, rejected, or missing. See forward_moving_average() for more info.
  • failed_validity (str, optional): Specifies the validity portion of the quality code for failed values Must be one of "M" (Missing), "R" (Rejected) or "Q" (Questionable). Values flagged as missing also have the value modified to math.nan. Defaults to "M".
  • in_place (bool, optional): Specifies whether to modify this time series (True) or a copy of it. Defaults to False.
Raises:
  • TimeSeriesException: If any of the following are true:
    • The time series has no data
    • The window is invalid
    • failed_validity is not one of "M", "R", or "Q"
Returns:

TimeSeries: The screened time series

def screen_with_value_change_rate( self, min_reject_limit: float = nan, min_question_limit: float = nan, max_question_limit: float = nan, max_reject_limit: float = nan, in_place: bool = False) -> TimeSeries:

Screens a time series - either this one or a copy of this one - settting the quality codes to "Okay", "Missing", "Questionable" or "Rejected" based on specified criteria about the rate of change.

Arguments:
  • min_reject_limit (float, optional): The minimum change per minute from one value to the next (increasing or decreasing) that is not flagged as rejected. Defaults to math.nan (test disabled).
  • min_question_limit (float, optional): The minimum non-rejected change per minute from one value to the next (increasing or decreasing) that is not flagged as questioned. Defaults to math.nan (test disabled).
  • max_question_limit (float, optional): The maximum non-rejected change per minute from one value to the next (increasing or decreasing) that is not flagged as questioned. Defaults to math.nan (test disabled).
  • max_reject_limit (float, optional): The maximum change per minute from one value to the next (increasing or decreasing) that is not flagged as rejected. Defaults to -ath.nan (test disabled).
  • in_place (bool, optional): Specifies whether to modify and return this time series (True) or a copy of this time series (False). Defaults to False.
Raises:
  • TimeSeriesException: If this time series has no data, or if:
    • min_reject_limit (if not math.nan) is not less than min_question_limit (if not math.nan) or max_reject_limit (if not math.nan)
    • min_question_limit (if not math.nan) is not less than max_question_limit (if not math.nan) or max_reject_limit (if not math.nan)
    • max_question_limit (if not math.nan) is not less thatn max_reject_limit (if not math.nan)
Returns:

TimeSeries: The screened time series

def screen_with_value_range( self, min_reject_limit: float = nan, min_question_limit: float = nan, max_question_limit: float = nan, max_reject_limit: float = nan, in_place: bool = False) -> TimeSeries:

Screens a time series - either this one or a copy of this one - settting the quality codes to "Okay", "Missing", "Questionable" or "Rejected" based on specified criteria about the value magnitudes.

Arguments:
  • min_reject_limit (float, optional): The minimum value that is not flagged as rejected. Defaults to -math.nan (test disabled).
  • min_question_limit (float, optional): The minium non-rejected value that is flagged as questionable. Defaults to -math.nan (test disabled).
  • max_question_limit (float, optional): The maxium non-rejected value that is flagged as questionable. Defaults to -math.nan (test disabled).
  • max_reject_limit (float, optional): The minimum value that is not flagged as rejected. Defaults to -math.nan (test disabled).
  • in_place (bool, optional): Specifies whether to modify and return this time series (True) or a copy of this time series (False). Defaults to False.
Raises:
  • TimeSeriesException: If this time series has no data, or if:
    • min_reject_limit (if not math.nan) is not less than min_question_limit (if not math.nan) or max_reject_limit (if not math.nan)
    • min_question_limit (if not math.nan) is not less than max_question_limit (if not math.nan) or max_reject_limit (if not math.nan)
    • max_question_limit (if not math.nan) is not less than max_reject_limit (if not math.nan)
Returns:

TimeSeries: The screened time series

def screen_with_value_range_or_change( self, min_limit: float = nan, max_limit: float = nan, change_limit: float = nan, replace_invalid_value: bool = True, invalid_value_replacement: float = nan, invalid_validity: str = 'M', in_place: bool = False) -> TimeSeries:

Screens a time series - either this one or a copy of this one - setting values and/or quality codes where the values are outside the specified range or differ more than the specified change.

Arguments:
  • min_limit (float): The minimum valid value. Values below this value will have their values and/or quality codes changed. Defaults to math.nan (test disabled).
  • max_limit (float): The maximum valid value. Values above this value will have their values and/or quality codes changed. Defaults to math.nan (test disabled).
  • change_limit (float): The maxium valid change from one value to the next. Values whose change (either increasing or decreasing) is greater that is will have their values and/or quality codes changed. Defaults to math.nan (test disabled).
  • replace_invalid_value (bool, optional): Replace screened-out values with the specified value. Defaults to True.
  • invalid_value_replacement (float, optional): The value to replace screen-out values with if replace_invalid_value=True. Defaults to math.nan (missing value).
  • invalid_validity (str, optional): Specifies the validity component of the quality code for screened-out values. May be "M" (Missing), "Q" (Questionable), or "R" (Rejected). Values flagged as missing also have the value modified to math.nan. Defaults to "M".
  • in_place (bool, optional): Specifies whether to modify and return this time series (True) or a copy of this time series (False). Defaults to False.
Raises:
  • TimeSeriesException: If the time series has no data or f invalid_validity (if specified) is not 'M', 'Q', or 'R'.
Returns:

TimeSeries: The screened time series

def select( self, selection: Union[Select, int, slice, Callable[[TimeSeriesValue], bool]], combination: Combine = <Combine.REPLACE: 1>, in_place: bool = False) -> TimeSeries:

Marks individual items in this object - or a copy of this object - as selected for pariticpation the next operation, either directly or by combining each item's current selected state with the result of a function. On creation the selection is cleared (i.e., every item is selected)

This object's selection_state property determines the selection of this object after the next operation:

Arguments:
  • selection (Union[Select, int, slice, Callable[[TimeSeriesValue], bool]]): One of the following:
    • Select.NONE: Marks all items as unselected. Any combination is ignored.
    • Select.ALL: Marks all items as selected. Any combination is ignored.
    • Select.INVERT: Inverts the current selected state of each item. Any combination is ignored.
    • integer: An integer offset from the beginning of the time series
    • HecTime object: single item matching specified time
    • datetime object: single item matching specified time
    • string convertible to HecTime object: : single item matching specified time
    • slice: One or more items.
      • The start parameter (if specified) and stop parameter may be:
        • integers - offsets from the first value in the time series
        • HecTime objects
        • datetime objects
        • strings convertible to HecTime objects
      • The step parameter must be an integer, if specified
    • function: A function that takes a single TimeSeriesValue parameter and returns a bool result. An item is marked as selected if and only if the result of the function is True for the item (when combined with the current state if necessary).
  • combination (Combine, optional): Specifies how to combine the function result with an item's current selected state. Used when selection is not one of eh Select values. Defaults to Combine.REPLACE.
    • Combine.REPLACE: Current selected state of each item is ignored and is replaced by the result of the function.
    • Combine.AND: Current selected state of each item is ANDed with the result of the function to generate new selected state.
    • Combine.OR: Current selected state of each items is ORed with the result of the function to generate new selected state.
    • Combine.XOR: Current selected state of each item is XORed with the result of the function to generate new selected state.
  • in_place (bool, optional): Specifies whether to mark itmes in this object (True) or a copy of this object (False). Defaults to False.
Raises:
  • TimeSeriesException: If this object has no data
  • ValueError: If an invalid selection or combination is specified.
Returns:

TimeSeries: The marked object

def select_valid(self, in_place: bool = False) -> TimeSeries:

Marks individual items in this object - or a copy of this object - as selected for pariticpation the next operation based on whether the items are valid. Items are valid unless any of the following are true:

  • The quality is MISSING
  • The quality is REJECTED
  • The value is NaN
  • The value is Infinite

This selection replaces any other selection - if it is to be combined with other selection criteria it must be performed before the other criteria

This object's selection_state property indicates/determines whether the selection is cleared af the next operation (via an automatic ts.select(Select.NONE)) or maintained until explicitly modified.

Arguments:
  • in_place (bool, optional): Specifies whether to mark itmes in this object (True) or a copy of this object (False). Defaults to False.
Raises:
  • TimeSeriesException: If this object has no data
Returns:

TimeSeries: The marked object

selected: list[bool]

The current selection (empty if all items are selected)

Operations:

Read Only

selection_state: SelectionState

The persistence state of selections in this object.

The default selection_state of SelectionState.TRANSIENT

Operations:

Read/Write

@classmethod
def set_default_slice_stop_exclusive(cls, state: bool = True) -> None:

Set the default slicing behavior of new TimeSeries objects

Arguments:
  • state (bool, optional): Defaults to True.
    • True: python behavior (stop value is excluded)
    • False: DataFrame behavior (stop value is included)
@classmethod
def set_default_slice_stop_inclusive(cls, state: bool = True) -> None:

Set the default slicing behavior of new TimeSeries objects

Arguments:
  • state (bool, optional): Defaults to True.
    • True: DataFrame behavior (stop value is included)
    • False: python behavior (stop value is excluded)
def set_duration( self, value: Union[Duration, str, int], in_place: bool = False) -> TimeSeries:

Sets the Duration for this time series, or a copy of it, and returns the modified time series

Arguments:
  • value (Union[Duration, str]): * Interval: The Duration object to use
    • str: The duration name
    • int: The (actual or characteristic) number of minutes for the duration
  • in_place (bool): Specifies whether to modify and return this time series (True) or a copy of this time series. Defaults to False.
Returns:

TimeSeries: The modified time series

def set_interval( self, value: Union[Interval, str, int], in_place: bool = False) -> TimeSeries:

Sets the interval for this time series, or a copy of it, and returns the modified time series

Arguments:
  • value (Union[Interval, str]): * Interval: The Interval object to use
    • str: The interval name
    • int: The (actual or characteristic) number of minutes for the interval
  • in_place (bool): Specifies whether to modify and return this time series (True) or a copy of this time series. Defaults to False.
Returns:

TimeSeries: The modified time series

def set_location( self, value: Union[Location, str], in_place: bool = False) -> TimeSeries:

Sets the location for this time series or a copy of it and returns the modified time series

Arguments:
  • value (Union[Location, str]): * Location: The Location object to use
    • str: The location name (may be in the format <office>/<location> to set office)
  • in_place (bool): Specifies whether to modify and return this time series (True) or a copy of this time series. Defaults to False.
Returns:

TimeSeries: The modified time series

def set_parameter( self, value: Union[Parameter, str], in_place: bool = False) -> TimeSeries:

Sets the parameter for this time series or a copy of it, and returns the modified time series

Arguments:
  • value (Union[Parameter, str]): * Parameter: The Parameter object to use
    • str: The parameter name - the unit will be set to the default English unit
  • in_place (bool): Specifies whether to modify and return this time series (True) or a copy of this time series. Defaults to False.
Returns:

TimeSeries: The modified time series

def set_parameter_type( self, value: Union[ParameterType, str], in_place: bool = False) -> TimeSeries:

Sets the parameter type for this time series, or a copy of it, and returns the modified time series

Arguments:
  • value (Union[ParameterType, str]): * ParameterType: The ParameterType object to use
    • str: The parameter type name
  • in_place (bool): Specifies whether to modify and return this time series (True) or a copy of this time series. Defaults to False.
Returns:

TimeSeries: The modified object

def set_protected(self, in_place: bool = False) -> TimeSeries:

Sets the quality protection bit of selected items of this time series - or a copy of it - and returns the modified time series.

Arguments:
  • in_place (bool, optional): Specifies whether to modify and return this time series (True) or a copy of this time series (False). Defaults to False.
Raises:
  • TimeSeriesException: If the time series has no data.
Returns:

TimeSeries: The modidified time series

def set_unprotected(self, in_place: bool = False) -> TimeSeries:

Un-sets the quality protection bit of selected items of this time series - or a copy of it - and returns the modified time series.

Arguments:
  • in_place (bool, optional): Specifies whether to modify and return this time series (True) or a copy of this time series (False). Defaults to False.
Raises:
  • TimeSeriesException: If the time series has no data.
Returns:

TimeSeries: The modidified time series

def set_quality( self, quality: Union[Quality, int], in_place: bool = False) -> TimeSeries:

Sets the quality of selected items of this object or a copy of this object

Arguments:
  • quality: Union[Quality, int]: The quality to set for selected items
  • in_place (bool): Specifies whether to set the values in this object (True) or a copy of this object (False)
Returns:

TimeSeries: The modified object

def set_unit( self, value: Union[pint.registry.Unit, str], in_place: bool = False) -> TimeSeries:

Sets the parameter unit for this time series, or a copy of it, and returns the modified time series.

NOTE: This does not modify any data values. Use the ito() method to modify data, which also sets the unit.

Arguments:
  • value (Union[Unit, str]):
    • Unit: The Unit object or name to use
    • str: The unit name
  • in_place (bool): Specifies whether to modify and return this time series (True) or a copy of this time series. Defaults to False.
Returns:

TimeSeries: The modified time series

def set_value(self, value: float, in_place: bool = False) -> TimeSeries:

Sets the value of selected items of this object or a copy of this object

Arguments:
  • value (float): The value to set for selected items
  • in_place (bool): Specifies whether to set the values in this object (True) or a copy of this object (False)
Returns:

TimeSeries: The modified object

def set_value_quality( self, value: float, quality: Union[Quality, int], in_place: bool = False) -> TimeSeries:

Sets the value and quality of selected items of this object or a copy of this object

Arguments:
  • value (float): The value to set for selected items
  • quality: Union[Quality, int]: The quality to set for selected items
  • in_place (bool): Specifies whether to set the values in this object (True) or a copy of this object (False)
Returns:

TimeSeries: The modified object

def set_vertical_datum_info( self, value: Union[str, dict[str, Any]], in_place: bool = False) -> TimeSeries:

Sets the vertical datum info for this time series, or a copy of it, and returns the modified time series

Arguments:
  • value (Union[str, dict[str, Any]]):
    • str: the vertical datum info as an XML string
    • dict: the vertical datum info as a dictionary
  • in_place (bool): Specifies whether to modify and return this time series (True) or a copy of this time series. Defaults to False.
Raises:

  • TimeSeriesException: If the base parameter is not "Elev"
Returns:

TimeSeries: The modified time series

slice_stop_exclusive: bool

Whether the stop portion of [start:stop] slicing is exclusive for this object.

  • If True, the slicing TimeSeries objects follows Python rules, where stop specifies the lowest index not included.
  • If False, the slicing of TimeSeries objects follows pandas.DataFrame rules, where stop specifies the highest index included.

The default value is determined by the class state, which defaults to True, but can be set by calling set_slice_stop_exclusive() or set_slice_stop_inclusive() before creating a TimeSeries object

Operations:

Read/Write

def snap_to_regular( self, interval: Union[Interval, str], offset: Union[TimeSpan, datetime.timedelta, str, NoneType] = None, backward: Union[TimeSpan, datetime.timedelta, str, NoneType] = None, forward: Union[TimeSpan, datetime.timedelta, str, NoneType] = None, in_place: bool = False) -> TimeSeries:

Modifies and returns a time series (either this one or a copy of this one) by snapping values to a specified regular interval (with an optional interval offset) and setting the interval to the one specified.

  • Only values within the forward and backward time spans around the new interval/offset will be included in the modified time series
  • If multiple values in the source time series are within the forward and backward time spans:
    • If some values are protected and others unprotected, the protected value closest to the snapping time is used.
    • If all or none of the values are protected:
      • If some values are valid and others invalid the valid value closest to the snapping time is used.
      • If all or none of the values are valid, the value closest to the snapping time is used.

This method does not respect selections. To snap based on a selection, first use the filter() or ifilter() method to genrate a time series from the selected values.

The resulting time series is always a regular time series, but if the time series has an attached time zone and interval is an Interval object with the is_local_regular property of True, then the resulting time series will be a Local Regular Time Series (LRTS).

The resulting time series will be a collapsed time series, with no values at times for which no values in the original time series were within the forward and backward time spans. The expand() method may be used to expand the collapsed time series.

Arguments:
  • interval (Union[Interval, str]): The new interval
  • offset (Optional[Union[TimeSpan, timedelta, str]]): The offset into the interval to snap the vlues to. Defaults to None.
  • backward (Optional[Union[TimeSpan, timedelta, str]]): The time span prior to the interval/offset to accept values from. Defaults to None.
  • forward (Optional[Union[TimeSpan, timedelta, str]]): The time span after the interval/offset to accept values from. Defaults to None.
  • in_place (bool, optional): Specifies whether to modify this time series (True) or a copy of it (False). Defaults to False.
Raises:
  • TimeSeriesException: If the specified interval is not a valid regular interval for the context of the time series. E.g., an irregular interval or a DSS-only regluar interval is specified for a CWMS time series
Returns:

TimeSeries: The modified time series

def time_derivative(self, in_place: bool = False) -> TimeSeries:

Returns a time series whose values are the differences of successive values in this time series divided by the number of minutes between the times of the values.

A missing value at a specific time in the source time series will cause the value at that and the next time in the result time sereies to be missing.

If a selection is present, all non-selected items are set to missing before the accumulation is computed. They remain missing in the retuned time series.

Restrictions * May be performed only on time series with differentiable base parameters. Use Parameter.differentiable_base_parameters() to list the accumulatable base parameters.

See base_parameter_definitions for information on base parameters and their conversions.

Arguments:
  • in_place (bool, optional): If True, this object is modified and retured, otherwise a copy of this object is modified and returned.. Defaults to False.
Raises:
  • TimeSeriesException: If the time series has no data.
Returns:

TimeSeries: The time series of time-based differences

time_zone: Optional[str]

The time zone of the data

Operations:

Read Only

times: list[str]

The times as a list of strings (empty if there is no data). Items are formatted as yyyy‑mm‑dd hh:mm:ss([+|‑]hh:mm)

Operations:

Read Only

def to( self, unit_parameter_or_datum: Union[str, pint.registry.Unit, Parameter], in_place: bool = False) -> TimeSeries:

Converts this object - or a copy of this object - to another unit, parameter, or vertical datum

Arguments:
  • unit_parameter_or_datum (Union[str, Unit, Parameter]): The unit, parameter or vertical datum to convert to
  • in_place (bool, optional): Whether to convert this object (True) or a copy of this object (False). Defaults to False.
Raises:
  • TimeSeriesException: If setting the vertical datum on a non Elev parameter or an Elev parameter without vertical datum information
Returns:

TimeSeries: The converted object

def to_irregular( self, interval: Union[Interval, str], in_place: bool = False) -> TimeSeries:

Sets a time series (either this one or a copy of this one) to a specified irregular interval, and returns the modified time series. The times of the data values are not changed.

Arguments:
  • interval (Union[Interval, str]): The irregular interval to set the time series to.
  • in_place (bool, optional): Specifies whether to modify this time series (True) or a copy of it (False). Defaults to False.
Raises:
  • TimeSeriesException: If the specified interval is not a valid irregular interval for the context of the time series (e.g., a regular interval or a DSS-only irregular interval for a CWMS time series)
Returns:

TimeSeries: The modified time series

def to_native(self, datastore: Any) -> Any:

Returns a copy of this time series in the native format of the specified data store.

Arguments:
  • datastore (Any): The datastore that specifies the native format
    • If an instance of CwmsDataStore, a cwms.cwms_types.Data object suitable for use with the cwms-python package is returned
    • If an instance of DssDataStore, an hecdss.RegularTimeSeries or hecdss.IrregularTimeSeries object suitable work use wth the hecdss package is returned
Raises:
  • TypeError: If datastore is not a valid data store type.
  • ValueError: If this time series is empty
Returns:

Any: The native time series.

def trim(self, in_place: bool = False) -> TimeSeries:

Trims a regular time series (either this one or a copy of this one), removing all missing values from the beginning and end of the time series unless they are either protected or marked as part of the current selection.

Irregular time series (including pseudo-regular time series) are not affected.

Does not alter any selection, even if selection state is SelectionState.TRANSIENT. Selected items remain selected after trim even though their location in the data may change.

Arguments:
  • in_place (bool, optional): Specifies whether to trim this time series (True) or a copy of this time series (False).
  • Defaults to False.
Returns:

TimeSeries: The trimmed time series

tsv: list[TimeSeriesValue]

The times, values, and qualities as a list of TimeSeriesValue objects (empty if there is no data)

Operations:

Read Only

unit: str

The parameter unit object

Operations:

Read Only

values: list[float]

The values as a list of floats (empty if there is no data)

Operations:

Read Only

version: Optional[str]

The version (HEC-DSS F pathname part)

Operations:

Read/Write

version_time: Optional[HecTime]

The version date/time

Operations:

Read/Write

vertical_datum_info: Optional[hec.parameter.ElevParameter._VerticalDatumInfo]

The vertical datum info object or None if not set

Operations:

Read Only

vertical_datum_info_dict: Optional[dict[str, Any]]

The vertical datum info as a dictionary or None if not set

Operations:

Read Only

vertical_datum_info_xml: Optional[str]

The vertical datum info as an XML string or None if not set

Operations:

Read Only

watershed: Optional[str]

The watershed (DSS A pathname part)

Operations:

Read/Write

class TimeSeriesException(builtins.Exception):

Exception specific to time series operations

@total_ordering
class TimeSeriesValue:

Holds a single time series value

TimeSeriesValue(time: Any, value: Any, quality: Union[Quality, int] = 0)

Initializes a TimeSeriesValue object

Arguments:
  • time (Any): The time. Must be an HecTime object or convertible to an HecTime object
  • value (Any): The value. Must be a UnitQuantity object or convertible to a UnitQuantity object
  • quality (Union[Quality, int], optional): The quality code. Must be a Quality object or a valid quality integer. Defaults to 0.
def equals(self, other: object, degree: int = 4) -> bool:

Returns whether two TimeSeriesValue objects are equal to the specified strictness. If the strictness indicates comparing the value fields, the comparison can use either of the following for value equality:

  • normal: equivalent values are considered equal even if they have different units. (e.g., 12 in == 1 ft)
  • strict: values must have same magnitude and units to be considered equal
Arguments:
  • other (object): The other TimeSeriesValue object to compare to
  • degree (int): Specifies how strict to make the comparison. Valid values are:
    • 1: Compares only time fields (same as == operator).
    • 2: Compares only time and value fields with normal value equality.
    • 3: Compares only time and value fields with strict value equality.
    • 4: Compares time, value, and quality fields with normal value equality.
    • 5: Compares time, value, and quality fields with stict value equality.
      Defaults to 4
Returns:

bool: Whether the time, value, and quality of two TimeSeriesValue objects are equal to the specified strictness.

is_valid: bool

Whether this object is valid. TimeSeriesValues are valid unless any of the following are True:

  • The quality is MISSING
  • The quality is REJECTED
  • The value is NaN
  • The value is Infinite
Operations:

Read-Write

quality: Quality

The Quality

Operations:

Read-Write

time: HecTime

The time

Operations:

Read-Write

value: UnitQuantity

The value

Operations:

Read-Write

@total_ordering
class TimeSpan:

Class to provide generic timespan capabilities that includes both calendar-based and non-calendar-based functionality. Internal fields are:

  • years
  • months
  • days
  • hours
  • minutes
  • seconds

Comparison/Contrast with timedelta

timedeltaTimeSpan
Does not support calendar-based operationsDoes support calendar-based operations
Does have sub-second resolutionDoes not have sub-second resolution
Can always be combined/compared with other timedelta objects
  • Can always be combined with other TimeSpan objects
  • Can be combined with timedelta objects if years and months are both zero
  • Can be compared with other TimeSpan objects if days values don't conflict with years or months values
  • Can be compared with timedelta objects if years and months are both zero

Fractional Months

Since HEC-DSS supports intervals of 1/3 and 1/2 month, the month portion of a TimeSpan object may be an integer or a Fraction object from the fractions package. Rules for using fractions are:

  • Fractions can be used for the month portion only
  • n/2 and n/3 are the only fractions allowed
  • Fractions can be specified as:
    • mathimatical expression (1/3)
    • Fraction object (Fraction(1,3))
    • string ("1/3")

Uninitialized Objects

Objects constructed without any initializer (e.g., ts = TimeSpan()) are initialized to be instantaneous (all values are zero).

String Representation

The repr function returns:

TimeSpan([years, months, days, hours, minutes, seconds])
The str function returns one or two ISO 8601 duration strings or pseudo-duration strings if the months value is a fraction.

  • If the object has both calendar- and non-calendar-based (non-zero) values, and the signs of those portions are different, the result will be one duration string for the calendar portion and one for the non-calendar portion, separated by a comma.
  • Otherwise the result will be a single duration string.
PT0S
P1Y2M3DT4H5M
-P1Y2M3DT4H5M
P1Y2M,-P3DT4H5M
-P1Y2M,P3DT4H5M
P3Y1/3M
-P2/3M
TimeSpan(*args: Any, **kwargs: Any)

Initialiazes the object at construction.

Arguments:
  • Default
    • TimeSpan() Initializes to default value of instantaneous (all values equal zero)
  • Positional

    • TimeSpan(timedelta)
    • TimeSpan(string) where string is:
      • an integer as a string
      • one or two ISO 8601 strings or pseudo-duration strings as discussed under String Representation
    • TimeSpan(list) where list contains 1..6 values interpreted as years, months, days, hours, minutes, and seconds. Values must be convertable via the int() function except for the second value, which may also be convertable via the Fraction() constructor.
    • TimeSpan(tuple) where tuple contains 1..6 values interpreted as years, months, days, hours, minutes, and seconds. Values must be convertable via the int() function except for the second value, which may also be convertable via the Fraction() constructor.
    • TimeSpan(years[,months[,days[,hours[,minutes[,seconds]]]]]) All values must be convertable via the int() function except for months, which may also be convertable via the Fraction() constructor.
  • Keyword:

    • TimeSpan([years=years,] [months=months,] [days=days,] [hours=hours,] [minutes=minutes,] [seconds=seconds]) All values must be convertable via the int() function except for months, which may also be convertable via the Fraction() constructor.
Raises:
  • TimeSpanException: if invalid initializers are specified
def set(self, *args: Any, **kwargs: Any) -> None:

Initialiazes or re-initializes the object.

Arguments:
  • Positional

    • set(timedelta)
    • set(string) where string is:
      • an integer as a string
      • one or two ISO 8601 strings or pseudo-duration strings as discussed under String Representation
    • set(list) where list contains 1..6 values interpreted as years, months, days, hours, minutes, and seconds. Values must be convertable via the int() function except for the second value, which may also be convertable via the Fraction() constructor.
    • set(tuple) where tuple contains 1..6 values interpreted as years, months, days, hours, minutes, and seconds. Values must be convertable via the int() function except for the second value, which may also be convertable via the Fraction() constructor.
    • set(years[,months[,days[,hours[,minutes[,seconds]]]]]) All values must be convertable via the int() function except for months, which may also be convertable via the Fraction() constructor.
  • Keyword:

    • set([years=years], [months=months], [days=days], [hours=hours], [minutes=minutes], [seconds=seconds]) All values must be convertable via the int() function except for months, which may also be convertable via the Fraction() constructor.
Raises:
  • TimeSpanException: if invalid initializers are specified
def timedelta(self) -> datetime.timedelta:

Returns an equivalent timedelta object

Raises:
  • TimeSpanException: if the object contains any calendar-based values
Returns:

timedelta: The equivalent timedelta object

def total_seconds(self) -> int:

Returns the total number of seconds represented by this object

Raises:
  • TimeSpanException: if the object contains any calendar-based values
Returns:

int: The total number of seconds

values: Optional[list[Union[int, fractions.Fraction]]]

A list of years, months, days, hours, minutes, and seconds in this time span. On read, all values will be normalized:

  • years and days are unconstrained in magnitude
  • integer months will be in the range of ±0..12
  • fractional months normalized
  • hours will be in the range of ±0..23
  • minutes and seconds will be in the range ±0..59
  • calendar-based values (years, months) will have the same sign if not zero
  • non-calendar-based values (days, hours, minutes, seconds) will have the same sign if not zero
  • calendar- and non-calendar-based values may have different signs
Operations:

Read/Write

class TimeSpanException(builtins.Exception):

Exception specific to TimeSpan operations

@total_ordering
class UnitQuantity:

Class for scalar values with units.

Thinly wraps pint.UnitRegistry.Quantity, but allows non-identifier unit names to be associated with quantities. Can be used with mathematical, comparison, and conversion operators in conjuction with pint.UnitRegistry.Quantity objects and scalars (ints and floats).

UnitQuantity(*args: Any)

Creates a UnitQuantity object

Arguments:
  • One argument:
    • str: Either:
    • UnitQuantity: Another UnitQuantity object
    • pint.Quantity: A Pint Quantity object
  • Two arguments:
    • args[0] (Union[int, float, Fraction]): The magnitude of the quantity
    • args[1] (Union[str, pint.Unit): The uni of the quantity
Raises:
  • UnitException: if in valid arguments are specified
dimensionality: pint.util.UnitsContainer

The dimensionality of the object

Operations:

Read/Only

def get_compatible_base_parameters(self, parameter_context: str = 'CWMS') -> list[str]:

Returns a list of base parameter names that are compatible with this object.

Arguments:
  • parameter_context (str, optional): Currently only "CWMS" is supported. Defaults to "CWMS".
Returns:

list[str]: _description_

def get_compatible_units(self) -> list[str]:

Returns a list of compatible unit unit names for the specified unit of this object. Compatible units are those that have the same dimensionality.

Returns:

list[str]: The list of compatible unit names for this object's specified unit

def get_unit_aliases(self) -> list[str]:

Returns a list of unit aliases for the specified unit of this object

Returns:

list[str]: The list of unit aliases for this object's specified unit

def get_unit_systems(self) -> list[str]:

Returns a list of unit systems that include the name of this unit.

Returns:

list[str]: Will be [], ['EN'], ['SI'], or ['EN', 'SI']

isnan: bool

Whether the magnitude of the objed is NaN

Operations:

Read/Only

def ito(self, unit: Union[str, pint.registry.Unit]) -> UnitQuantity:

Converts this object to a different unit in place.

Identical to calling .to(..., in_place=True)

Arguments:
  • unit (Union[str, pint.Unit]): The unit ot convert to
Returns:

UnitQuantity: The converted object

magnitude: float

The magnitude of the object (unitless value)

Operations:

Read/Only

output_format: Optional[str]

The output format used for this object if a format specifier is not used. Any format specifier used will override this property.

If None, the unit name or alias specified when the object was creaed will be output (e.g., 10 dsf). See Pint format specification for other formats.

Operations:

Read/Write

def round(self, places: int = 0) -> UnitQuantity:

Returns a copy of this object with the magnitude rounded to the specified number of decimal places

Arguments:
  • places (int): The number of decimal places to round to. Default is 0.
Returns:

UnitQuantity: The rounded object

@classmethod
def set_default_output_format(cls, format: Optional[str]) -> None:

Sets the default output format for new UnitQuantity objects

Arguments:
  • format (Optional[str]):
    • None: (default value) outputs the units as specified when the UnitQuantity object was created
    • Other: Must be a valid Pint format specification
specified_unit: str

The unit specified when the object was created. May be a unit name, alias, or a pint unit definition

Operations:

Read/Only

def to( self, unit: Union[str, pint.registry.Unit], in_place: bool = False) -> UnitQuantity:

Converts this object to a different unit

Arguments:
  • unit (Union[str, pint.Unit]): The unit to convert to
  • in_place (bool, optional): If True, this object is modified and returned. Otherwise a new object is returned. Defaults to False.
Returns:

UnitQuantity: The converted object

unit: pint.registry.Unit

The Pint unit of the object

Operations:

Read/Only

class UnitException(builtins.Exception):

Exception specific to Unit operations

class UsgsRounder:

Provides functionality of USGS rounding arrays (called rounding specifications in this package). The full description of using rounding arrays can be found in Section 3.5 (Data Rounding Convention) of the ADAPS Section of the National Water Information System User's Manual.

Specifically, the rounding specifications are strings of 10 digits with the following meanings (left to right):

  1. Number of significant digits for values < 0.01
  2. Number of significant digits for values >= 0.01 and < 0.1
  3. Number of significant digits for values >= 0.1 and < 1.0
  4. Number of significant digits for values >= 1.0 and < 10
  5. Number of significant digits for values >= 10 and < 100
  6. Number of significant digits for values >= 100 and < 1000
  7. Number of significant digits for values >= 1,000 and < 10,000
  8. Number of significant digits for values >= 10,000 and < 100,000
  9. Number of significant digits for values >= 100,000
  10. Maximum number of decimal places regardless of magnitude
UsgsRounder(rounding_spec: str = '4444444444')
rounding_spec: str
def round_f( self, values: Sequence[float], round_half_even: bool = True) -> list[float]:
def round_s(self, values: Sequence[float], round_half_even: bool = True) -> list[str]: