Date and Time Features
A timestamp such as 2026-03-14 18:45:00 is one value to a database, but a model cannot use it as it is: as a single number (seconds since 1970) it only says "later", and most of what matters is hidden inside it. Is it a weekend? Evening rush hour? The last day of the month, when salaries arrive? Two days before a public holiday? Date/time decomposition turns one timestamp into the handful of features that carry those patterns. Parsing and time zones belong to cleaning (Dates, Times and Units); this lesson starts from clean, timezone-aware timestamps.
What to extract
| Feature | From 2026-03-14 18:45 |
Captures |
|---|---|---|
| year, month, day | 2026, 3, 14 | trend, season, pay-day effects |
| day of week, weekend flag | 5 (Saturday), 1 | weekly rhythm |
| hour, minute | 18, 45 | daily rhythm |
| day of year, week of year | 73, 11 | yearly season |
| month start / month end flags | 0, 0 | billing and salary cycles |
| holiday, days to next holiday | from a calendar table | special days |
| elapsed time | days since sign-up, age from date of birth | lifetime, maturity |
Elapsed-time features are often the strongest: "account age 3 days" says far more than the sign-up date itself. Always compute them relative to the moment of prediction, never relative to "today" when the script happens to run, or the feature changes every time you retrain.
Decomposing with pandas
import pandas as pd
pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)
orders = pd.DataFrame({
"placed_at": pd.to_datetime(["2026-03-13 08:10", "2026-03-14 18:45", "2026-03-31 23:50",
"2026-04-01 00:05", "2026-12-24 12:00"]),
"customer_since": pd.to_datetime(["2024-01-02", "2026-03-10", "2019-07-21", "2026-03-30", "2025-12-24"]),
})
t = orders["placed_at"].dt
features = pd.DataFrame({
"month": t.month, "day": t.day, "weekday": t.dayofweek, "weekend": (t.dayofweek >= 5).astype(int),
"hour": t.hour, "doy": t.dayofyear, "month_end": t.is_month_end.astype(int),
"tenure_days": (orders["placed_at"] - orders["customer_since"]).dt.days,
})
holidays = pd.to_datetime(["2026-04-03", "2026-12-25"])
features["days_to_holiday"] = [int(min((h - d.normalize()).days for h in holidays if h >= d.normalize()))
for d in orders["placed_at"]]
print(features) month day weekday weekend hour doy month_end tenure_days days_to_holiday
0 3 13 4 0 8 72 0 801 21
1 3 14 5 1 18 73 0 4 20
2 3 31 1 0 23 90 1 2445 3
3 4 1 2 0 0 91 0 2 2
4 12 24 3 0 12 358 0 365 1
Look at rows 2 and 3: fifteen minutes apart in reality, but month, day, doy and month_end all jump. This is the problem the next section solves.
Cyclical features: hour 23 is next to hour 0
Hour, weekday and month are cyclical: after 23 comes 0, after December comes January. As plain integers, 23 and 0 are as far apart as possible. The fix maps a value with period to a point on the unit circle:
Both coordinates are needed: the sine alone gives the same value for 3 o'clock and 9 o'clock (it is symmetric about 6), the pair is unique. Now the Euclidean distance between two hours depends only on how far apart they are around the clock: for hours and it is , using the shorter way round.
import numpy as np
def cyclic(v, period):
angle = 2 * np.pi * np.asarray(v) / period
return np.column_stack([np.sin(angle), np.cos(angle)])
hours = np.array([0, 1, 6, 12, 23])
enc = cyclic(hours, 24)
print("hour sin cos")
for h, (s, c) in zip(hours, enc):
print(f"{h:4d} {s:7.3f} {c:7.3f}")
def dist(a, b):
return float(np.linalg.norm(cyclic([a], 24) - cyclic([b], 24)))
print("raw |23 - 0| =", abs(23 - 0), "| circle distance 23-0:", round(dist(23, 0), 3), "| 0-12:", round(dist(0, 12), 3))hour sin cos
0 0.000 1.000
1 0.259 0.966
6 1.000 0.000
12 0.000 -1.000
23 -0.259 0.966
raw |23 - 0| = 23 | circle distance 23-0: 0.261 | 0-12: 2.0
On the circle, 23:00 and 00:00 are 0.261 apart, exactly as close as 00:00 and 01:00, while midnight and noon are the maximum distance 2 apart.
Does it matter to a model?
A bike-rental counter peaks around 08:00 and 18:00 and is near zero at night. A linear model on the raw hour can only fit one straight line through the day. On the sine/cosine pair (plus the second harmonic, the same pair for , which allows two peaks) it can follow the daily shape. Both versions run in the same pipeline, with the encoding as a FunctionTransformer:
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score, KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer
rng = np.random.default_rng(3)
hour = rng.integers(0, 24, 600)
demand = (40 * np.exp(-((hour - 8) ** 2) / 4) + 55 * np.exp(-((hour - 18) ** 2) / 6)
+ 8 + rng.normal(0, 5, 600))
def harmonics(h):
a = 2 * np.pi * np.asarray(h).ravel() / 24
return np.column_stack([np.sin(a), np.cos(a), np.sin(2 * a), np.cos(2 * a)])
cv = KFold(5, shuffle=True, random_state=0)
X = hour.reshape(-1, 1)
raw = cross_val_score(Ridge(), X, demand, cv=cv, scoring="r2").mean()
cyc = cross_val_score(make_pipeline(FunctionTransformer(harmonics), Ridge()), X, demand, cv=cv, scoring="r2").mean()
print(f"raw hour: R2 = {raw:.3f}")
print(f"sin/cos harmonics: R2 = {cyc:.3f}")raw hour: R2 = 0.107
sin/cos harmonics: R2 = 0.714
The raw hour explains almost nothing (cross-validated of 0.107); the harmonics reach 0.714. A tree-based model would do well on the raw hour too, because it can cut the day into intervals; cyclical encoding matters most for linear models, neural networks and distance-based methods. For several harmonics or splines, scikit-learn's SplineTransformer(extrapolation="periodic") is a ready-made alternative.
Pitfalls
- Time zones: "hour of day" in UTC is the wrong rhythm for a customer in Hanoi. Convert to local time before extracting, and keep the zone in the data.
- Features from the future: "days until the order was delivered" is not known when the order is placed. Only use timestamps that exist at prediction time.
- The raw timestamp as a feature: a model trained on 2024-2025 sees only values it has never seen when used in 2026; trees extrapolate it as "the latest period", linear models extrapolate the trend. Prefer elapsed times and cyclical parts.
- Random splits on time-stamped data hide all of this. Validate on a later period (split strategies, time-series preparation).
Practice
- Encode the month (1 to 12) cyclically. What are the coordinates for March, and which month is diametrically opposite to it?
Answer
and , so March is . Opposite is six months later, September, at . (With months 1 to 12, December maps to angle , the same point as a month "0"; that is fine, January follows it.)
- A churn model uses
signup_date. Suggest two better features.
Answer
Tenure at prediction time (prediction_date - signup_date in days) and the sign-up cohort's season or channel if relevant. The raw date only lets the model memorise periods.
Test yourself
Why encode the hour of day with both sine and cosine?
- Sine alone is too small
- Sine alone maps different hours (for example 3 and 9) to the same value; the pair is unique
- Cosine is required by scikit-learn
- To scale the feature
With the cyclical encoding (period 24), which pair of hours is closest?
- 0 and 12
- 6 and 18
- 23 and 0
- 0 and 6
Which feature is safe for predicting, at order time, whether an order will be returned?
- Days between order and delivery
- Days since the customer signed up, measured at order time
- Whether the customer called support after delivery
- The refund date
Which model gains the most from cyclical hour features compared with the raw hour?
- A deep decision tree
- A linear model
- A random forest
- None, it never matters