## StepDatetimeFeatures


Expand Datetime columns into calendar-part feature columns.


Usage

``` python
StepDatetimeFeatures(
    columns,
    *,
    features=_DEFAULT_DATETIME_FEATURES,
    categorical=(),
    keep_original_cols=False,
    role="feature",
    id=None
)
```


Each selected Datetime column is replaced by one integer column per requested entry of [features](Selectors.md#mlfeatures.Selectors.features) (`year`, `month`, `day`, `hour`, `minute`, `second`, `dow`, `doy`), named `{column}_{feature}`. Nothing is estimated from the training data: every calendar part is an elementwise function of the column's value, so the transform is identical on training and new data.

`dow` is the ISO day of week (`1` = Monday, `7` = Sunday); `doy` is the ordinal day of year (`1`-`366`). Produced columns are `Int32` regardless of backend, unless named in [categorical](Selectors.md#mlfeatures.Selectors.categorical).

Calendar parts are read against whatever time zone the column already carries (including none); this step does not convert to a different zone. A caller who needs a specific zone should convert it first, e.g. with `narwhals.Expr.dt.convert_time_zone()` inside a [StepMutate](StepMutate.md#mlfeatures.StepMutate).

A Date column (with no time-of-day component) is not accepted here; use [StepDateFeatures](StepDateFeatures.md#mlfeatures.StepDateFeatures) for those.

See [Value Extraction](https://feaz-book.com/datetime-extraction) in *Feature Engineering A to Z* for background on this technique.

See [Arguments shared across steps](../user-guide/common-step-arguments.md) for the arguments this step shares with the others.


## Parameters


`columns: Selector`  
Columns to expand. Accepts a single column name, a list of names, a mlfeatures selector such as [Selectors.datetime_features()](Selectors.md#mlfeatures.Selectors.datetime_features) (see [Selectors](Selectors.md#mlfeatures.Selectors) for the full set), or a narwhals or polars selector (`narwhals.selectors.by_dtype(narwhals.Datetime)`). Selectors are resolved against the data frame's schema when the recipe is fitted, so the same selector works on any backend. Only Datetime columns are meaningful here.

`features: list[str] | tuple[str, …] = _DEFAULT_DATETIME_FEATURES`\  
Calendar parts to compute, from `"year"`, `"month"`, `"day"`, `"hour"`, `"minute"`, `"second"`, `"dow"` (day of week), and `"doy"` (day of year). Default `("year", "month", "day", "hour", "minute", "second", "dow", "doy")`. Deduplicated and reordered to that same canonical order regardless of the order passed in, so the output columns are always in a fixed order.

`categorical: list[str] | tuple[str, …] = ()`\  
Subset of [features](Selectors.md#mlfeatures.Selectors.features), restricted to `"month"` and `"dow"` (the two parts with a natural, fixed vocabulary of level names), to encode as an ordered categorical column of level names (`"January"`, `"Monday"`, …) instead of a plain integer. Default `()`: no feature is categorical. Each entry must also be present in [features](Selectors.md#mlfeatures.Selectors.features).

`keep_original_cols: bool = ``False`  
If `True`, the source columns are kept alongside their calendar-part columns instead of being dropped. Default `False`.

`role: str | None = ``"feature"`  
Role assigned to the new calendar-part columns (see [Roles](Roles.md#mlfeatures.Roles)). Default `"feature"`.

`id: str | None = None`  
Stable step identifier. Defaults to `"datetime_features"`; a second step of this type in the same recipe becomes `"datetime_features_2"`, and passing an `id` already used in the recipe is an error.


## Examples

Each selected column is replaced by its calendar-part columns:


``` python
df = pd.DataFrame(
    {
        "dt": [
            datetime(2020, 1, 1, 8, 30, 0),
            datetime(2020, 6, 15, 13, 45, 30),
            datetime(2020, 12, 31, 23, 59, 59),
        ]
    }
)
df
```


|     | dt                  |
|-----|---------------------|
| 0   | 2020-01-01 08:30:00 |
| 1   | 2020-06-15 13:45:30 |
| 2   | 2020-12-31 23:59:59 |


Specifying the step touches no data:


``` python
recipe = Recipe().add(StepDatetimeFeatures(s.datetime_features()))
recipe
```


    Recipe (untrained)
      Inputs: no roles assigned
      Steps:
        step_datetime_features(select(role='feature', type=Datetime))  [untrained]


There is nothing to estimate, so [fit()](Step.fit.md#mlfeatures.Step.fit) only resolves the selection:


``` python
fitted = recipe.fit(df)
fitted
```


    Recipe (trained)
      Inputs: 8 columns (8 features)
      Steps:
        step_datetime_features(dt → dt_year, dt_month, dt_day, dt_hour, dt_minute, dt_second, dt_dow, dt_doy)  [trained]


[transform()](Step.transform.md#mlfeatures.Step.transform) adds one column per requested calendar part and drops the source:


``` python
fitted.transform(df)
```


|     | dt_year | dt_month | dt_day | dt_hour | dt_minute | dt_second | dt_dow | dt_doy |
|-----|---------|----------|--------|---------|-----------|-----------|--------|--------|
| 0   | 2020    | 1        | 1      | 8       | 30        | 0         | 3      | 1      |
| 1   | 2020    | 6        | 15     | 13      | 45        | 30        | 1      | 167    |
| 2   | 2020    | 12       | 31     | 23      | 59        | 59        | 4      | 366    |


A narrower [features](Selectors.md#mlfeatures.Selectors.features) produces fewer columns:


``` python
recipe = Recipe().add(
    StepDatetimeFeatures(s.datetime_features(), features=["year", "month", "hour"])
)
fitted = recipe.fit(df)
fitted.transform(df)
```


|     | dt_year | dt_month | dt_hour |
|-----|---------|----------|---------|
| 0   | 2020    | 1        | 8       |
| 1   | 2020    | 6        | 13      |
| 2   | 2020    | 12       | 23      |


[keep_original_cols](Step.keep_original_cols.md#mlfeatures.Step.keep_original_cols) keeps the source column alongside the calendar parts:


``` python
recipe = Recipe().add(
    StepDatetimeFeatures(s.datetime_features(), keep_original_cols=True)
)
fitted = recipe.fit(df)
fitted.transform(df)
```


|  | dt | dt_year | dt_month | dt_day | dt_hour | dt_minute | dt_second | dt_dow | dt_doy |
|----|----|----|----|----|----|----|----|----|----|
| 0 | 2020-01-01 08:30:00 | 2020 | 1 | 1 | 8 | 30 | 0 | 3 | 1 |
| 1 | 2020-06-15 13:45:30 | 2020 | 6 | 15 | 13 | 45 | 30 | 1 | 167 |
| 2 | 2020-12-31 23:59:59 | 2020 | 12 | 31 | 23 | 59 | 59 | 4 | 366 |


[categorical](Selectors.md#mlfeatures.Selectors.categorical) names level names instead of raw numbers for `month` and `dow`:


``` python
recipe = Recipe().add(
    StepDatetimeFeatures(s.datetime_features(), categorical=["month", "dow"])
)
fitted = recipe.fit(df)
fitted.transform(df)
```


|     | dt_year | dt_month | dt_day | dt_hour | dt_minute | dt_second | dt_dow    | dt_doy |
|-----|---------|----------|--------|---------|-----------|-----------|-----------|--------|
| 0   | 2020    | January  | 1      | 8       | 30        | 0         | Wednesday | 1      |
| 1   | 2020    | June     | 15     | 13      | 45        | 30        | Monday    | 167    |
| 2   | 2020    | December | 31     | 23      | 59        | 59        | Thursday  | 366    |
