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
pd.Series|pd.Index|list|tuple|pd.DatetimeIndex|npt.NDArray The coordinate values to convert to datetime
- coord_name
str, optional The name of the coordinate dimension (default: “date”)
- validate_non_numericbool, optional
Whether to validate that values are not numeric dtype. Set to False when intentionally converting numeric time indices. Default: True
- coords_values
- Returns:
pd.DatetimeIndexThe converted datetime index
- Raises:
ValueErrorIf 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)