Timestamps (dv.times)

Timestamp sanitizing, frequency detection, resampling and formatting.

Imported as diive.times, reached as dv.times after import diive as dv.

TIMES: TIMESTAMP HANDLING

Public namespace dv.times: timestamp sanitizing, frequency detection, date ranges and resampling.

Part of the diive library: https://github.com/holukas/diive

diive.times.resample_to_daily_agg(series, agg='mean', mincounts_perc=0.0)[source]

Resample a time series to one aggregated value per calendar day.

Aggregates a (typically sub-daily) time series down to daily resolution, e.g. a daily-mean time series over the record. Days that hold too few records can be dropped via mincounts_perc.

Parameters:
  • series (Series) – Time series with a DatetimeIndex.

  • agg (str) – Aggregation method, anything pandas’ Series.agg accepts (e.g. 'mean', 'sum', 'median', 'min', 'max', 'std'). Defaults to 'mean'.

  • mincounts_perc (float) – Minimum fraction (0-1) of the fullest day’s record count that a day must reach to be kept. 0 (default) keeps every day that has at least one value; 0.9 keeps only days at least 90 % complete relative to the most-populated day.

Return type:

Series

Returns:

Daily-aggregated Series, indexed by day (timestamp at day start), with the input series’ name preserved.

Raises:

TypeError – If series does not have a DatetimeIndex.

See also

examples/times/times_resample_daily.py — daily aggregation with several methods

diive.times.resample_to_monthly_agg_matrix(series, agg, ranks=False)[source]

Resample to monthly aggregation across years, store results in a matrix.

Parameters:
  • series (Series) – Time series with timestamp.

  • agg (str) – Method for monthly aggregation, e.g. agg=’mean’. Allowed methods: ‘mean’, ‘median’, ‘sum’, ‘max’, ‘min’, ‘std’, ‘skew’.

  • ranks (bool) – Returns ranks of aggregation values in the matrix. For example, if agg=’mean’ and ranks=True, then the highest value in each month across years is attributed rank 1, the second highest rank 2, etc. For measurements such as air temperature, rank 1 means that the respective month was the warmest across all years.

Return type:

DataFrame

Returns:

Matrix with resampled data. The resulting dataframe has YEAR as index and MONTH as columns.

class diive.times.DetectFrequency(index, verbose=False)[source]

Bases: object

Detect data time resolution from time series index

Two regular timestamps are enough, since they define one interval. An index with a single timestamp defines no interval at all and therefore raises RuntimeError, same as an index that is too irregular to detect.

Three methods run: pandas infer_freq on the full index, the most frequent time step, and infer_freq on chunks at the start and end of the index. After construction, freq (also returned by get()), confidence (0-1), detection_method, percent_matching and alternatives describe the result.

Parameters:
  • index (DatetimeIndex) – Timestamp index to check.

  • verbose (bool) – Print the detected frequency.

  • Example: examples/times/times_frequency_detection.py

  • Tests: tests/test_time.py

__init__(index, verbose=False)[source]

Set up frequency detection for an index. See the class docstring.

Parameters:
get()[source]

Return the detected frequency string.

Return type:

str

class diive.times.TimestampSanitizer(data, output_middle_timestamp=True, validate_naming=True, convert_to_datetime=True, remove_index_nat=True, sort_ascending=True, remove_duplicates=True, regularize=True, nominal_freq=None, verbose=False)[source]

Bases: object

Validate and prepare timestamps for time series data processing.

Cleans and validates datetime indices in 10 steps: naming convention, format conversion, NaT/duplicate removal, sorting, monotonicity validation, frequency detection, gap filling (optional), and middle-of-period conversion (optional). Each step can be enabled or disabled independently.

The processing pipeline (in order): 1. Validate timestamp naming convention 2. Convert timestamp index to datetime format 3. Remove rows with missing timestamps (NaT) 4. Sort timestamp in ascending order 5. Remove duplicate timestamps (keep last) 6. Validate timestamp monotonicity (if sorting enabled) 7. Detect time resolution from timestamp 8. Validate detected frequency against expected frequency (if provided) 9. Make timestamp continuous (records off the time grid are removed and counted) 10. Convert to middle-of-period timestamp (optional)

Variables:
  • data (Union[Series, DataFrame]) – The processed data with validated timestamp index.

  • inferred_freq (str) – Detected time resolution of the timestamp index.

Raises:
  • TypeError – If data is None or not a Series/DataFrame.

  • ValueError – If data is empty, has no valid index, or timestamp naming is invalid.

  • ValueError – If nominal_freq does not match detected frequency.

  • RuntimeError – If the time resolution cannot be detected (see DetectFrequency).

Parameters:

Warning

  • Regularization side effect: When regularize=True, gaps are filled with NaN data rows. This may increase the number of rows significantly. The grid follows the position within the time step that most records share, so one stray or late record does not move it. Records that are not on the grid (for example 1-min records in 10-min data) are removed. Their number is shown as a warning and reported as ‘rows_removed_off_grid’ in get_status(). The warning is shown also with verbose=False, unless the global verbosity is silent.

  • Processing runs in the constructor: if a step raises, no sanitized data are returned. The input data are not changed.

  • Frequency detection: Detection raises RuntimeError if timestamps are too irregular. nominal_freq=None skips only the comparison with the expected frequency, not the detection itself.

See also

examples

__init__(data, output_middle_timestamp=True, validate_naming=True, convert_to_datetime=True, remove_index_nat=True, sort_ascending=True, remove_duplicates=True, regularize=True, nominal_freq=None, verbose=False)[source]

Initialize TimestampSanitizer and process timestamp index.

Parameters:
  • data (Union[Series, DataFrame]) – Data with timestamp index to be validated and processed.

  • output_middle_timestamp (bool) – Convert timestamp index to show middle of averaging period. Default is True.

  • validate_naming (bool) – Check if timestamp is correctly named. Allowed names are ‘TIMESTAMP_END’, ‘TIMESTAMP_START’, and ‘TIMESTAMP_MIDDLE’. Default is True.

  • convert_to_datetime (bool) – Convert timestamp index to datetime format. Default is True.

  • remove_index_nat (bool) – Remove rows without timestamp (NaT values). Default is True.

  • sort_ascending (bool) – Sort timestamp in ascending order. Default is True.

  • remove_duplicates (bool) – Remove duplicate timestamps (keep last occurrence). Default is True.

  • regularize (bool) – Generate continuous timestamp without date gaps. Records that are not on the time grid are removed and counted. Default is True.

  • nominal_freq (str) – Expected time resolution of data timestamp index. If provided, detected frequency is validated against this. Raises ValueError if they don’t match. Examples: ’10s’, ‘5s’, ‘s’, ‘30min’, ‘5min’, ‘min’, ‘1h’, ‘3h’, ‘h’. Default is None (no frequency validation).

  • verbose (bool) – Print status messages during processing. Default is False.

Examples

>>> import diive as dv, pandas as pd
>>> idx = pd.date_range('2024-06-01 00:30', periods=48, freq='30min', name='TIMESTAMP_END')
>>> df = pd.DataFrame({'TA': range(48)}, index=idx)
>>> clean = dv.times.TimestampSanitizer(data=df, nominal_freq='30min').get()

See examples/times/times_timestamp_sanitizer.py for clean data, minor issues, badly broken timestamps, and selective processing.

get()[source]

Return the sanitized DataFrame.

Return type:

Union[Series, DataFrame]

get_status()[source]

Return processing status and summary of changes made.

Returns a dictionary with information about what was modified during timestamp sanitization, useful for understanding data loss or changes.

Returns:

Dictionary with keys:

  • ’original_shape’: Original data shape (rows, columns)

  • ’final_shape’: Final data shape after processing

  • ’rows_removed’: Total rows removed during cleaning

  • ’rows_removed_nat’: Rows removed due to NaT values

  • ’rows_removed_duplicates’: Duplicate rows removed

  • ’rows_removed_off_grid’: Rows removed by regularization because their timestamp is not on the time grid

  • ’rows_added_by_regularization’: Rows added to fill gaps

  • ’net_rows’: Final row count minus original row count (can be negative)

  • ’inferred_frequency’: Detected time resolution

  • ’frequency_confidence’: Confidence score for detected frequency (0.0-1.0)

  • ’frequency_detection_method’: Method used to detect frequency

  • ’frequency_percent_matching’: % of intervals matching detected frequency

  • ’frequency_alternatives’: Alternative frequencies detected by other methods

  • ’timestamp_format’: Index name (TIMESTAMP_END, TIMESTAMP_START, or TIMESTAMP_MIDDLE)

Return type:

dict

Example

>>> import diive as dv, pandas as pd
>>> idx = pd.date_range('2024-06-01 00:30', periods=48, freq='30min', name='TIMESTAMP_END')
>>> sanitizer = dv.times.TimestampSanitizer(pd.DataFrame({'TA': range(48)}, index=idx))
>>> status = sanitizer.get_status()  # rows_removed, frequency_confidence, ...
diive.times.format_timestamp(data, convention, fmt=None, verbose=False)[source]

Build a timestamp Series for a chosen averaging-interval convention.

Derives a START, MIDDLE or END timestamp from data’s (timestamp) index without modifying that index. The returned Series is aligned to the input index, so it can be added to data as a new data column while the index keeps its own convention (typically TIMESTAMP_MIDDLE).

The START/END shift reuses insert_timestamp(), so the input index must be a properly named, regular timestamp index (‘TIMESTAMP_START’, ‘TIMESTAMP_MIDDLE’ or ‘TIMESTAMP_END’) with a known frequency.

Parameters:
  • data (Union[DataFrame, Series, DatetimeIndex]) – Source whose index supplies the timestamps. A DataFrame/Series (its index is used) or a DatetimeIndex directly.

  • convention (Literal['start', 'middle', 'end']) – Convention of the produced timestamps: - ‘start’: start of the averaging interval - ‘middle’: middle of the averaging interval - ‘end’: end of the averaging interval

  • fmt (Optional[str]) – Optional strftime format string (e.g. '%Y%m%d%H%M' for the FLUXNET convention). If given, the Series holds formatted strings; if None, it holds datetime64 values.

  • verbose (bool) – If True, gives additional text output.

Return type:

Series

Returns:

A Series named ‘TIMESTAMP_START’, ‘TIMESTAMP_MIDDLE’ or ‘TIMESTAMP_END’, aligned to data’s index.

Examples

>>> import diive as dv, pandas as pd
>>> idx = pd.date_range('2024-06-01 00:15', periods=4, freq='30min', name='TIMESTAMP_MIDDLE')
>>> df = pd.DataFrame({'TA': range(4)}, index=idx)
>>> df['TS'] = dv.times.format_timestamp(df, convention='start', fmt='%Y%m%d%H%M')

Added in: v0.92.0

diive.times.insert_timestamp(data, convention, insert_as_first_col=True, verbose=False, set_as_index=False)[source]

Insert timestamp column that shows the START, END or MIDDLE time of the averaging interval

The new timestamp column is added as data column, the current data index remains unchanged. A DataFrame is not copied: the column is also added to the DataFrame that was passed in.

The current data index must be a properly named timestamp index. Allowed names are: ‘TIMESTAMP_START’, ‘TIMESTAMP_MIDDLE’, ‘TIMESTAMP_END’.

Parameters:
  • data (DataFrame) – Dataset to which the new timestamp is added as new column

  • convention (Literal['start', 'middle', 'end']) – Timestamp convention of the new timestamp column - ‘start’: Timestamp denoting start of averaging interval - ‘middle’: Timestamp denoting middle of averaging interval - ‘end’: Timestamp denoting end of averaging interval

  • insert_as_first_col (bool) – If True, the new timestamp column is added as the first column to data. If False, the new timestamp column is added as the last column to data.

  • set_as_index (bool) – Sets the new timestamp column as dataframe index.

  • verbose (bool) – If True, gives additional text output

Return type:

DataFrame

Returns:

data with newly added timestamp column

Added in: v0.52.0

diive.times.keep_daterange(data, start=None, end=None, verbose=False)[source]

Keep only records whose timestamp falls within [start, end] (inclusive).

A non-destructive date-range subselection: returns a copy restricted to the given window, leaving the input untouched so the caller can keep the full record and revert. Either bound may be omitted to leave that side open.

Parameters:
  • data (Union[Series, DataFrame]) – Series or DataFrame with a DatetimeIndex.

  • start – Lower bound (inclusive). A pandas.Timestamp, datetime, or any string pandas can parse (e.g. '2021-06-01', '2021-06-01 12:30'). None leaves the start open.

  • end – Upper bound (inclusive), same accepted types as start. None leaves the end open.

  • verbose (bool) – Print how many records were kept.

Return type:

Union[Series, DataFrame]

Returns:

A copy of data containing only the in-range records. With both bounds None the full data is returned (as a copy).

Raises:

See also

examples/times/times_keep_daterange.py — date-range subselection examples

diive.times.validate_timestamp_column_name(name, convention)[source]

Reject a reserved timestamp name that contradicts the column’s convention.

The names ‘TIMESTAMP_START’, ‘TIMESTAMP_MIDDLE’ and ‘TIMESTAMP_END’ are reserved: each one states which point of the averaging interval its timestamps mark. Naming a column with one of them while its values follow a different convention would mislabel the data (and could be misread downstream), so it is not allowed. Any other name is accepted.

Parameters:
  • name (str) – The intended column name.

  • convention (Literal['start', 'middle', 'end']) – The convention the column’s timestamps actually follow (‘start’, ‘middle’ or ‘end’).

Raises:

ValueError – If name is a reserved timestamp name for a different convention than convention.

Return type:

None

diive.times.timestamp_infer_freq_from_fullset(timestamp_ix)[source]

Infer frequency from the complete timestamp index using pandas inference.

Analyzes all timestamps to detect regular sampling patterns. This method uses pandas’ built-in frequency inference and is most reliable for strictly regular data without gaps or irregular intervals.

Parameters:

timestamp_ix (DatetimeIndex) – Timestamp index to analyze.

Returns:

(inferred_freq, freqinfo)

  • inferred_freq : str or None Detected frequency string (e.g., ‘30min’, ‘1h’), or None if detection failed.

  • freqinfo : str Detection result (‘full data’ if successful, ‘-not-enough-datarows-’ if <10 rows, ‘-failed-’ if inference failed).

Return type:

tuple

Notes

  • Requires at least 10 timestamps for analysis

  • Most reliable for perfectly regular, gap-free data

  • Returns None if data has irregular intervals or gaps

  • Use in combination with other methods for robust detection

diive.times.timestamp_infer_freq_from_timedelta(timestamp_ix)[source]

Infer frequency from the most common interval between successive timestamps.

Calculates differences between consecutive timestamps and identifies the most frequent interval. This method is robust to minor irregularities and works even when data has small gaps or occasional interval variations, as long as one interval dominates (>50% of observations).

Parameters:

timestamp_ix (DatetimeIndex) – Timestamp index to analyze.

Returns:

(inferred_freq, freqinfo)

  • inferred_freq : str or None Detected frequency string (e.g., ‘30min’, ‘1h’), or None if no interval appears in >50% of all intervals.

  • freqinfo : str Detection result with statistics (e.g., ‘100% occurrence’), ‘-not-enough-datarows-’ if there is no interval to measure (fewer than 2 timestamps, or none of the deltas is valid), or ‘-failed-’ if no interval dominates.

Return type:

tuple

Notes

  • Requires at least 2 timestamps (to calculate one interval)

  • Robust to occasional irregular intervals

  • Returns frequency only if most common interval covers >50% of all intervals (n timestamps give n-1 intervals)

  • Useful for data with small gaps or timing variations

References

diive.times.timestamp_infer_freq_progressively(timestamp_ix)[source]

Infer frequency by comparing first and last intervals of timestamp index.

Checks if the first N rows and last N rows have the same frequency, starting with N=1000 and progressively reducing to N=4. If both match, the frequency is consistent throughout the dataset. This method is fast and robust for detecting regular sampling patterns even in large datasets.

Parameters:

timestamp_ix (DatetimeIndex) – Timestamp index to analyze.

Returns:

(inferred_freq, freqinfo)

  • inferred_freq : str or None Detected frequency string (e.g., ‘30min’, ‘1h’), or None if detection failed.

  • freqinfo : str or None Detection method description (‘data N+N’ if successful, None otherwise).

Return type:

tuple

Notes

  • Requires at least 8 rows (4 from start, 4 from end) for detection

  • Returns frequency only if start and end intervals match

  • Useful for quick frequency validation before full dataset analysis