safe_to_datetime#

pymc_marketing.mmm.additive_effect.safe_to_datetime(coords_values, coord_name='date', validate_non_numeric=True)[source]#

Safely convert coordinates to datetime, with validation.

This function prevents the issue where numeric values (e.g., [0, 1, 2, 3]) get incorrectly converted to dates starting from January 1st 1970 with nanosecond intervals.

Parameters:
  • coords_values (Series | Index | list | tuple | DatetimeIndex | NDArray) – The coordinate values to convert to datetime

  • coord_name (str) – The name of the coordinate dimension (default: “date”)

  • validate_non_numeric (bool) – Whether to validate that values are not numeric dtype. Set to False when intentionally converting numeric time indices. Default: True

Return type:

pd.DatetimeIndex

Returns:

The converted datetime index

Raises:

ValueError – If the coordinate values have numeric dtype and validate_non_numeric is True

Examples

>>> # Good usage - string dates
>>> safe_to_datetime(["2024-01-01", "2024-01-02"])
>>> # Good usage - already datetime
>>> safe_to_datetime(pd.to_datetime(["2024-01-01", "2024-01-02"]))
>>> # Raises error - numeric values with validation
>>> safe_to_datetime([0, 1, 2, 3])  # Raises ValueError
>>> # Allowed - numeric time indices with validation disabled
>>> safe_to_datetime([0, 1, 2, 3], validate_non_numeric=False)