lair.utils.clock#
Utility classes & functions for working with time and dates.
Functions
|
Convert the times from one timezone to another. |
|
Returns the datetime accessor of the object. |
|
Convert a decimal date to a datetime object. |
|
Aggregate the data to the specified frequency and compute the statistic for each group. |
|
Convert a datetime object to a decimal date. |
|
Convert a PeriodIndex to a list of bin edges. |
|
Convert an array of regular times to intervals of the specified length. |
|
Aggregate data by season and year. |
|
Calculate the time decay matrix for the specified times and decay. |
|
Calculate the time differences between each pair of times. |
Classes
|
TimeRange class to represent a time range with start and stop times. |
|
Time your code using a class, context manager, or decorator |
- class lair.utils.clock.TimeRange(time_range: TimeRange | str | list[str | datetime | None] | tuple[str | datetime | None, str | datetime | None] | slice | None = None, start: str | list[str | datetime | None] | tuple[str | datetime | None, str | datetime | None] | slice | None | datetime = None, stop: str | list[str | datetime | None] | tuple[str | datetime | None, str | datetime | None] | slice | None | datetime = None)[source]#
TimeRange class to represent a time range with start and stop times.
Attributes
start
(dt.datetime | None) The start time of the time range.
stop
(dt.datetime | None) The stop time of the time range.
total_seconds
(float) The total number of seconds in the time range.
Methods
parse_iso(string: str, inclusive: bool = False) -> dt.datetime
Parse the ISO8601 formatted time string and return a datetime object.
- __init__(time_range: TimeRange | str | list[str | datetime | None] | tuple[str | datetime | None, str | datetime | None] | slice | None = None, start: str | list[str | datetime | None] | tuple[str | datetime | None, str | datetime | None] | slice | None | datetime = None, stop: str | list[str | datetime | None] | tuple[str | datetime | None, str | datetime | None] | slice | None | datetime = None)[source]#
Initialize a TimeRange object with the specified time range.
- Parameters:
- time_rangestr | list[Union[str, dt.datetime, None]] | tuple[Union[str, dt.datetime, None], Union[str, dt.datetime, None]] | slice | None
_description_, by default None
- startUnion[_input_types, dt.datetime], optional
_description_, by default None
- stopUnion[_input_types, dt.datetime], optional
_description_, by default None
- Raises:
- ValueError
_description_
- static parse_iso(string: str, inclusive: bool = False) datetime [source]#
Parse the ISO8601 formatted time string and return a namedtuple with the parsed components.
- Parameters:
- stringstr
The ISO8601 formatted time string.
- inclusive
- Returns:
- dt.datetime
The parsed datetime object.
- Raises:
- ValueError
If the time_str format is invalid.
- class lair.utils.clock.Timer(name: str | None = None, text: str = 'Elapsed time: {:0.4f} seconds', logger: ~typing.Callable[[str], None] | None = <built-in function print>)[source]#
Time your code using a class, context manager, or decorator
https://realpython.com/python-timer
- logger(*args, sep=' ', end='\n', file=None, flush=False)#
Prints the values to a stream, or to sys.stdout by default.
- sep
string inserted between values, default a space.
- end
string appended after the last value, default a newline.
- file
a file-like object (stream); defaults to the current sys.stdout.
- flush
whether to forcibly flush the stream.
- lair.utils.clock.datetime_accessor(obj, accessor='dt')[source]#
Returns the datetime accessor of the object.
- lair.utils.clock.regular_times_to_intervals(times, time_step='monthly', closed='left') IntervalIndex [source]#
Convert an array of regular times to intervals of the specified length.
- Parameters:
- timesnp.array
A numpy array of datetime64 values indicating the start of each interval.
- time_stepstr, optional
The interval step (‘hourly’, ‘daily’, ‘monthly’, ‘annual’). Determines the length of each interval. Default is ‘monthly’.
- closedstr, optional
Defines if the interval is closed on the ‘left’, ‘right’, ‘both’, or ‘neither’. Default is ‘left’.
- Returns:
- pd.IntervalIndex
An index with intervals covering the specified time range.
- Raises:
- ValueError
If time_step is not one of ‘hourly’, ‘daily’, ‘monthly’, or ‘annual’.
- lair.utils.clock.periodindex_to_binedges(periodindex: PeriodIndex) list[Timestamp] [source]#
Convert a PeriodIndex to a list of bin edges.
- Parameters:
- periodindexpd.PeriodIndex
The PeriodIndex to convert.
- Returns:
- list[pd.Timestamp]
The bin edges.
- lair.utils.clock.time_difference_matrix(times, absolute: bool = True) ndarray [source]#
Calculate the time differences between each pair of times.
- Parameters:
- timeslist[dt.datetime]
The list of times to calculate the differences between.
- absolutebool, optional
If True, return the absolute differences. Default is True.
- Returns:
- np.ndarray
The matrix of time differences.
- lair.utils.clock.time_decay_matrix(times, decay: str | Timedelta) ndarray [source]#
Calculate the time decay matrix for the specified times and decay.
- Parameters:
- timeslist[dt.datetime]
The list of times to calculate the decay matrix for.
- decaystr | pd.Timedelta
The decay to use for the exponential decay.
- Returns:
- np.ndarray
The matrix of time decay values.
- lair.utils.clock.diurnal(data: DataFrame, freq: str = '1H', statistic: str = 'mean', method: Literal['floor', 'ceil', 'round'] = 'floor')[source]#
Aggregate the data to the specified frequency and compute the statistic for each group.
- Parameters:
- datapd.DataFrame
The data to aggregate. Panda DataFrame with a DateTimeIndex.
- freqstr
The frequency to aggregate the data to. Sub-Daily.
- statisticstr or list of str, optional
The statistic to compute for each group. Default is ‘mean’.
- methodone of ‘floor’, ‘ceil’, ‘round’
The method to use to round the index to the nearest freq.
- Returns:
- pd.DataFrame
The aggregated data.
- lair.utils.clock.seasonal(data: DataFrame, statistic: str = 'mean') DataFrame [source]#
Aggregate data by season and year.
- Parameters:
- datapd.DataFrame
The data to aggregate. Panda DataFrame with a DateTimeIndex.
- statisticstr, optional
The statistic to compute for each group. Default is ‘mean’.
- Returns:
- pd.DataFrame
The aggregated data.
- lair.utils.clock.dt2decimalDate(datetime: datetime) float [source]#
Convert a datetime object to a decimal date.
- Parameters:
- datetimedt.datetime
The datetime object to convert.
- Returns:
- float
The decimal date.
- lair.utils.clock.decimalDate2dt(decimalDate: float) datetime [source]#
Convert a decimal date to a datetime object.
- Parameters:
- decimalDatefloat
The decimal date to convert.
- Returns:
- dt.datetime
The datetime object.
- lair.utils.clock.convert_timezones(x, totz, fromtz=None, localize=False, driver=None)[source]#
Convert the times from one timezone to another.
- Parameters:
- xlist[dt.datetime] | pd.DataFrame | pd.Series
The times to convert.
- totzstr
The timezone to convert the times to.
- fromtzstr, optional
The timezone of the input times, by default None
- localizebool, optional
If True, the times will be localized to the totz timezone, by default False
- Returns:
- list[dt.datetime] | pd.DataFrame | pd.Series
The converted times.
- lair.utils.clock.UTC2(x, totz, *, fromtz='UTC', localize=False, driver=None)#
Convert the times from one timezone to another.
- Parameters:
- xlist[dt.datetime] | pd.DataFrame | pd.Series
The times to convert.
- totzstr
The timezone to convert the times to.
- fromtzstr, optional
The timezone of the input times, by default None
- localizebool, optional
If True, the times will be localized to the totz timezone, by default False
- Returns:
- list[dt.datetime] | pd.DataFrame | pd.Series
The converted times.
- lair.utils.clock.UTC2MST(x, *, totz='MST', fromtz='UTC', localize=False, driver=None)#
Convert the times from one timezone to another.
- Parameters:
- xlist[dt.datetime] | pd.DataFrame | pd.Series
The times to convert.
- totzstr
The timezone to convert the times to.
- fromtzstr, optional
The timezone of the input times, by default None
- localizebool, optional
If True, the times will be localized to the totz timezone, by default False
- Returns:
- list[dt.datetime] | pd.DataFrame | pd.Series
The converted times.
- lair.utils.clock.UTC2MTN(x, *, totz='America/Denver', fromtz='UTC', localize=False, driver=None)#
Convert the times from one timezone to another.
- Parameters:
- xlist[dt.datetime] | pd.DataFrame | pd.Series
The times to convert.
- totzstr
The timezone to convert the times to.
- fromtzstr, optional
The timezone of the input times, by default None
- localizebool, optional
If True, the times will be localized to the totz timezone, by default False
- Returns:
- list[dt.datetime] | pd.DataFrame | pd.Series
The converted times.
- lair.utils.clock.MST2UTC(x, *, totz='UTC', fromtz='MST', localize=False, driver=None)#
Convert the times from one timezone to another.
- Parameters:
- xlist[dt.datetime] | pd.DataFrame | pd.Series
The times to convert.
- totzstr
The timezone to convert the times to.
- fromtzstr, optional
The timezone of the input times, by default None
- localizebool, optional
If True, the times will be localized to the totz timezone, by default False
- Returns:
- list[dt.datetime] | pd.DataFrame | pd.Series
The converted times.
- lair.utils.clock.MTN2UTC(x, *, totz='UTC', fromtz='America/Denver', localize=False, driver=None)#
Convert the times from one timezone to another.
- Parameters:
- xlist[dt.datetime] | pd.DataFrame | pd.Series
The times to convert.
- totzstr
The timezone to convert the times to.
- fromtzstr, optional
The timezone of the input times, by default None
- localizebool, optional
If True, the times will be localized to the totz timezone, by default False
- Returns:
- list[dt.datetime] | pd.DataFrame | pd.Series
The converted times.