Skip to content

cyclical_time_features

cyclical_time_features

cyclical_time_features(timestamps: Any, *, fields: tuple[str, ...] = ('hour', 'dayofweek', 'month')) -> DataFrame

Encode calendar fields as (sin, cos) pairs: the one everyone re-implements.

Periodic time variables (hour-of-day, day-of-week, month) are discontinuous as raw integers (23:00 is adjacent to 00:00 but 23 is far from 0); sin/cos on the circle fixes that. Pass any datetime-like (Series / Index / array); returns two columns per field.

Parameters:

Name Type Description Default
fields tuple of str

Any of minute, hour, dayofweek, day, month, dayofyear.

('hour', 'dayofweek', 'month')

Returns:

Type Description
DataFrame

{field}_sin / {field}_cos per requested field, aligned to the input order.

See Also

temporal_context_features : Calendar context (weekend, time block).

Examples:

>>> import pandas as pd
>>> ts = pd.to_datetime(["2026-01-01T00:00Z", "2026-01-01T06:00Z"])
>>> out = cyclical_time_features(ts, fields=("hour",))
>>> out.columns.tolist()
['hour_sin', 'hour_cos']
>>> round(float(out["hour_sin"].iloc[1]), 1)
1.0
Source code in src/gbfs_toolkit/analytics/temporal.py
def cyclical_time_features(
    timestamps: Any, *, fields: tuple[str, ...] = ("hour", "dayofweek", "month")
) -> pd.DataFrame:
    """Encode calendar fields as (sin, cos) pairs: the one everyone re-implements.

    Periodic time variables (hour-of-day, day-of-week, month) are discontinuous as raw integers
    (23:00 is adjacent to 00:00 but ``23`` is far from ``0``); sin/cos on the circle fixes that.
    Pass any datetime-like (Series / Index / array); returns two columns per field.

    Parameters
    ----------
    fields : tuple of str
        Any of ``minute, hour, dayofweek, day, month, dayofyear``.

    Returns
    -------
    pandas.DataFrame
        ``{field}_sin`` / ``{field}_cos`` per requested field, aligned to the input order.

    See Also
    --------
    [`temporal_context_features`][gbfs_toolkit.temporal_context_features] : Calendar context (weekend, time block).

    Examples
    --------
    >>> import pandas as pd
    >>> ts = pd.to_datetime(["2026-01-01T00:00Z", "2026-01-01T06:00Z"])
    >>> out = cyclical_time_features(ts, fields=("hour",))
    >>> out.columns.tolist()
    ['hour_sin', 'hour_cos']
    >>> round(float(out["hour_sin"].iloc[1]), 1)
    1.0
    """
    ts = pd.to_datetime(
        pd.Series(list(timestamps) if not hasattr(timestamps, "dt") else timestamps)
    )
    ts = ts.reset_index(drop=True)
    out: dict[str, np.ndarray] = {}
    for f in fields:
        if f not in _CYCLE_PERIODS:
            raise ValueError(f"unknown field {f!r}; choose from {sorted(_CYCLE_PERIODS)}")
        angle = 2 * np.pi * getattr(ts.dt, f).to_numpy() / _CYCLE_PERIODS[f]
        out[f"{f}_sin"] = np.sin(angle)
        out[f"{f}_cos"] = np.cos(angle)
    return pd.DataFrame(out)