Sub topic 8
Extracting features from dates and times
This chapter assumes you know pandas basics, how a scikit-learn fit/transform workflow runs, and why transformations must be fitted on training data only. A raw timestamp is rarely useful to a model. Its parts often are.
Why raw timestamps fail
A datetime column is stored as a point on a timeline. Most models cannot use it directly. Converted to a number such as seconds since 1970, it only tells the model "later or earlier". Patterns that repeat, such as busy mornings or quiet Sundays, stay hidden.
The fix is to ask what in the timestamp could matter for the target, then extract it. Domain knowledge drives this choice.
Calendar parts
First make sure the column has a datetime type. Then use the .dt accessor.
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)Useful parts include year, month, day of week, hour, and flags such as weekend, month end, or public holiday. Holidays need an external calendar, and they depend on the country.
Cyclical features
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. Sine and cosine place the hours on a circle, so neighbours stay close.
You need both columns. Sine alone maps two different hours to the same value, and cosine alone does the same. Together they identify each hour uniquely. Use the cycle length as the divisor: 24 for hours, 7 for day of week, 12 for month.
Tree-based models can split on the raw hour and handle wrap-around by using several splits. Cyclical encoding helps most for linear models, k-nearest neighbours, and neural networks.
Elapsed time and differences
Often the most predictive value is a duration, not a calendar part. Examples are days since signup, days since the last purchase, or the gap between two events.
df["signup"] = pd.to_datetime(["2023-01-15", "2023-06-01"])
df["days_since_signup"] = (df["ts"] - df["signup"]).dt.daysCompute durations against a fixed reference that is available at prediction time. Do not use pd.Timestamp.now() when building training data, because the value changes on every run and cannot be reproduced.
Common errors
- Random splits on time-ordered data. If you predict the future, validate on later rows than you train on. A random split lets the model see the future.
- Time zones. Convert to one zone before extracting hour or day. A midnight event in UTC is evening in New York.
- Using the raw hour in a linear model. The model treats it as a straight line and misses the wrap-around.
- Features built from future data. "Days until the next event" may be unknown when the model runs in production.
Using these steps in a pipeline
Pure calendar extraction learns nothing from the data, so it cannot leak. You can wrap it in a FunctionTransformer and place it inside a ColumnTransformer. That keeps training and serving code identical.
Exercise
Why do you need both a sine column and a cosine column to encode the hour of day, and why not use the raw hour for a linear model?
Show answer
Sine alone gives the same value for two different hours (for example hours 6 and 12 on the circle share a sine of 1 and 0 only at certain points, and each sine value occurs twice per day), so the hour cannot be recovered. Adding cosine makes each hour a unique point on the circle. The raw hour is a straight line from 0 to 23, so a linear model sees hours 23 and 0 as far apart even though they are adjacent.