Sub topic 8
Extracting features from dates and times
This chapter assumes you know basic pandas, the scikit-learn fit and transform workflow, and the leakage rule from the earlier chapter: every learned quantity is fitted on training data only. Date-time columns need little fitting. Most of the work is deciding which parts of a timestamp matter, and keeping those decisions consistent between training and serving.
Why raw timestamps are poor features
A model cannot use a string such as "2024-03-01 08:15:00". Converting it to a single number, such as seconds since 1970, gives the model something it can read. But that number only increases, and most real patterns are not about "how many seconds have passed". They are about:
- Calendar position. Hour of day, day of week, month, quarter.
- Calendar events. Weekends, holidays, month-end, payday.
- Elapsed time. Days since signup, time since the last purchase.
- Order. Which events came before others.
Feature engineering here means turning a timestamp into the quantities that carry these patterns.
Step one: parse and extract calendar parts
Parse the column with pd.to_datetime first. Then use the .dt accessor to pull out parts.
import numpy as np
import pandas as pd
df = pd.DataFrame({"ts": ["2024-03-01 08:15:00", "2024-03-02 23:40:00"]})
df["ts"] = pd.to_datetime(df["ts"])
df["hour"] = df["ts"].dt.hour
df["dayofweek"] = df["ts"].dt.dayofweek
df["is_weekend"] = (df["dayofweek"] >= 5).astype(int)
# cyclical encoding so that hour 23 is close to hour 0
df["hour_sin"] = np.sin(2 * np.pi * df["hour"] / 24)
df["hour_cos"] = np.cos(2 * np.pi * df["hour"] / 24)Pandas numbers weekdays from Monday as 0 to Sunday as 6, so >= 5 marks Saturday and Sunday. Other .dt attributes you will use often are month, day, quarter, dayofyear, is_month_end and is_quarter_start.
If parsing fails on mixed formats, pass an explicit format= argument. If some values are bad, errors="coerce" turns them into NaT (not a time). Treat NaT as a missing value and handle it as described in the missing-values chapter. Do not silently drop those rows.
Cyclical encoding
Hour 23 and hour 0 are one hour apart, but as plain integers they are 23 apart. A linear model or a neural network sees a large gap that does not exist. Mapping the value onto a circle fixes this. With period P (24 for hours, 7 for weekdays, 12 for months), you create two columns:
sin(2π · value / P)cos(2π · value / P)
You need both columns. Sine alone gives the same value for two different hours, for example hours 4 and 8. The pair of values identifies each point on the circle uniquely. In the code above, hour 8 maps to about (0.87, −0.50) and hour 23 maps to about (−0.26, 0.97).
When is this worth doing?
| Model family | Raw integer hour | Sine and cosine |
|---|---|---|
| Linear, logistic, SVM, neural network | Misleading at the wrap-around | Helpful |
| Decision trees, random forests, gradient boosting | Fine, splits can isolate any range | Rarely needed |
| Any model, when each hour behaves differently | One-hot encode instead | Cannot represent arbitrary shapes |
Sine and cosine can only express a single smooth daily wave. If demand peaks at 8 a.m. and again at 6 p.m., add harmonics (a second pair using 2 · 2π · hour / 24), or one-hot encode the hour.
Elapsed time and differences
Often the most predictive date feature is a difference between two timestamps, not the timestamp itself.
orders = pd.DataFrame({
"signup_ts": pd.to_datetime(["2024-01-05", "2024-02-10"]),
"order_ts": pd.to_datetime(["2024-03-01 12:00", "2024-03-02 18:30"]),
})
orders["days_since_signup"] = (
(orders["order_ts"] - orders["signup_ts"]).dt.total_seconds() / 86400
)Use total_seconds() rather than .dt.days when you want fractional days. The .days attribute truncates.
The common error here is computing "age" against datetime.now(). Run the same code a month later and every feature value shifts. A model trained on last month's values then sees a different scale at serving time. Anchor to a fixed reference date that you store with the model, or compute elapsed time between two columns in the same row, as above.
Time zones and daylight saving
"Hour of day" depends on whose clock you use. A purchase at 02:00 UTC is evening in New York. If behavior follows local time, convert before extracting parts.
utc = pd.Series(pd.to_datetime(["2024-03-10 02:00:00", "2024-03-10 14:00:00"]))
local = utc.dt.tz_localize("UTC").dt.tz_convert("America/New_York")
local_hour = local.dt.hourWatch for three problems:
- Naive timestamps. A column without time zone information is ambiguous. Find out from the data source what zone it uses, then call
tz_localize. - Daylight saving. Local clocks skip or repeat an hour twice a year. Local-hour features are still correct, but differences in local time are wrong. Compute durations in UTC.
- Mixed zones in one column. Convert everything to UTC first, then convert to the zone you care about, per user or per store if needed.
Holidays and events
Holidays and events are domain knowledge, not something the model can derive from the calendar. Use a calendar of known dates, such as pandas' USFederalHolidayCalendar or the holidays package, and create flags such as is_holiday and days_to_next_holiday. Add promotion dates and paydays if your business has them. For the "days to" features, a distance to the nearest event often works better than a plain flag, because effects ramp up before an event and fade after it.
Putting date features in a pipeline
Extraction functions with no learned parameters are safe from leakage by themselves. They still belong in the pipeline, so that training and serving run the same code. Wrap the function in a FunctionTransformer.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import FunctionTransformer
def calendar_features(X):
ts = pd.to_datetime(X["ts"])
return pd.DataFrame({
"is_weekend": (ts.dt.dayofweek >= 5).astype(int),
"hour_sin": np.sin(2 * np.pi * ts.dt.hour / 24),
"hour_cos": np.cos(2 * np.pi * ts.dt.hour / 24),
})
prep = ColumnTransformer([
("calendar", FunctionTransformer(calendar_features), ["ts"]),
])
X = pd.DataFrame({"ts": ["2024-03-01 08:15:00", "2024-03-02 23:40:00"]})
print(prep.fit_transform(X).shape) # (2, 3)Selecting ["ts"] as a list gives the function a one-column DataFrame, so X["ts"] works. You can add this step to the main ColumnTransformer next to the numeric and categorical branches.
Splitting data that has an order
Date-time columns bring a second risk. If rows have a time order, a random split lets the model train on the future and predict the past. Scores look good, then fall in production. Use a split that respects time: train on earlier rows, validate on later ones.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import TimeSeriesSplit, cross_val_score
# rows are assumed to be sorted by time already
X, y = make_classification(n_samples=500, random_state=0)
scores = cross_val_score(
LogisticRegression(max_iter=1000),
X, y,
cv=TimeSeriesSplit(n_splits=5),
scoring="roc_auc",
)
print(scores.round(3))TimeSeriesSplit assumes the rows are already sorted. Sort by timestamp before you call it. Also keep features from looking forward. A rolling mean of the last 7 days is fine. A centered rolling mean that includes tomorrow is leakage. When you build lag or rolling features with shift and rolling, check that every window ends at or before the row's own time.
Common errors
- Using the year as a trend. A model that learns
year = 2023cannot extrapolate to 2025. Tree models treat unseen years as "the latest bucket seen". Prefer elapsed time or drop the year. - Treating month as a continuous number. December and January are neighbors. Use cyclical or one-hot encoding for linear models.
- Leaving the raw timestamp in. A trees-based model may use it as an ID and memorize rows. Drop it after extraction.
- Extracting parts before converting zones. The hour is wrong for local behavior.
- Different code paths at serving time. Compute features with the same function in both places.
Exercise
A model predicts ride demand and uses hour of day as a plain integer 0 to 23 with logistic regression. Demand at 23:00 and 00:00 is nearly identical, but the model treats them as far apart. Name a fix, and say why one sine column is not enough.
Show answer
Encode hour as a point on a circle with two columns, sin(2π·hour/24) and cos(2π·hour/24). One sine column maps two different hours to the same value (for example hours 4 and 8), so the model cannot tell them apart. The cosine column separates them, and together the two columns give each hour a unique position where 23 and 0 are neighbors.
Exercise
You build a feature "customer age in days" as today's date minus the signup date, using the current date at the moment the code runs. Why does this cause train-serving skew, and how do you fix it?
Show answer
The value depends on when the code runs. Training data computed in January and serving data computed in June use different reference dates, so the same customer gets different values and the feature's scale drifts. Fix it by using a fixed reference stored with the model, or by computing elapsed time between two timestamps in the same row, such as order time minus signup time.