Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 106/ 160
06. Feature Engineering & Model Evaluation

Date-Time & Cyclical Feature Extraction

Extract calendar parts and encode cyclical hour/day signals with sin/cos features.

IntermediateCalendar Parts · sin/cos3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Dates and times hide patterns like busy hours or weekends, and for repeating things such as hours or months we encode them on a circle so the end of one cycle sits next to the start of the next.

Think of it like…

A clock face: 11 pm and 1 am are two hours apart even though 23 and 1 differ by 22 on a number line; sine and cosine put the hours on a circle so the model sees the true distance.

Where you’ve seen it

A ride-demand model starts with a raw timestamp. The team extracts hour, dayofweek, month, is_weekend, is_holiday (from a country calendar) and days_since_launch. Using hour as an integer, a linear model sees hours 23 and 0 as 23 units apart. With the cyclical encoding (sin(2πh/24), cos(2πh/24)) the points for 23:00 and 00:00 are a chord of length 2 sin(π/24) = 0.261 apart on the unit circle, while 6:00 maps to (1, 0), 12:00 to (0, −1) and 18:00 to (−1, 0), so opposite times are far apart and neighbours close. Adding the encoded hour and day-of-week features to a linear regression reduces MAE from 14.8 to 9.6 rides; a gradient-boosted model, which can split on hour directly, improves only from 8.1 to 7.9. Lag features (demand 24 and 168 hours ago) and a 7-day rolling mean add further gains, and the team keeps all timestamps in UTC, converts to local time for hour-of-day features and splits train and test by time so rolling features never include future rows.

Words you’ll hear

Calendar features
Hour, day, month, weekday, holiday flags and similar parts of a timestamp.
Cyclical encoding
Mapping a periodic value to sin and cos so the end of the cycle is next to the start.
Lag / rolling features
Past values or windowed aggregates used as predictors.
Elapsed time
Time since an event such as signup or last purchase.

Visual diagram

Loading interactive diagram

Theory & deep dive

Extracting calendar and elapsed-time features

With pandas, the .dt accessor provides hour, dayofweek, day, month, quarter, isocalendar().week, is_month_end and more. Add domain calendars: public holidays (holidays package), school terms, paydays, promotions, sports events and the days before and after holidays, since effects often start earlier. Elapsed-time features turn absolute timestamps into relative ones: days since signup, hours since the last event, time between events, age at the time of the event. These generalise better than raw dates, because a model trained on 2024 data should not rely on the literal year, and a monotonic year feature extrapolates poorly for tree models; prefer relative time or trend features designed for the problem.

Handle time zones carefully: store and compute in UTC, then convert to the user's or location's local time for features such as hour-of-day (a 03:00 UTC order is an evening order in California). Be aware of daylight saving (23-hour and 25-hour days), different weekend definitions, and parsing errors (day-first versus month-first). For irregular events, derive counts and rates over windows (orders in the last 7 and 30 days), and for durations, compute from consistent start and end times. Keep features available at prediction time: a feature like "total orders this month" computed with the full month is leakage if you predict mid-month.

Pandas extraction

df["hour"] = df.ts.dt.tz_convert("America/Los_Angeles").dt.hour; df["dow"] = df.ts.dt.dayofweek; df["days_since_signup"] = (df.ts - df.signup_ts).dt.days creates local-hour, weekday and tenure features from UTC timestamps.

Key takeaway: Extract calendar, holiday and elapsed-time features from UTC timestamps converted to local time, using only information available at prediction time.

Cyclical encoding and lag features

For a periodic variable t with period T (hour of day T = 24, day of week T = 7, month T = 12, day of year T = 365.25), create two features: sin(2πt/T) and cos(2πt/T). Together they locate the value on a circle: 6:00 → (sin, cos) = (1, 0); 12:00 → (0, −1); 18:00 → (−1, 0); 0:00 → (0, 1). Both are needed because sine alone maps two different times to the same value (3:00 and 9:00 both give sin = 0.707 when T = 24). The Euclidean distance between adjacent hours is a chord of length 2 sin(π/T) = 0.261 for T = 24, including 23:00 to 00:00, whereas the integer encoding says 23. Linear models, neural networks, KNN and SVMs benefit; tree-based models can split the raw integer anywhere and usually need no cyclical encoding, though it rarely hurts. For multiple seasonal shapes use several harmonics (sin and cos of 2πkt/T for k = 1, 2, 3) or Fourier features, as Prophet does.

Lag and rolling features summarise history: value at t − 1, t − 24, t − 168; rolling means, minima, maxima and standard deviations over 7 or 28 days; rate of change; exponentially weighted averages. Compute them with groupby(entity).shift() and rolling() so each row only uses earlier data (and for multi-step forecasts, only data that would exist at forecast time: with a 7-day horizon a lag of 3 days isn't available). Evaluate with time-based splits, never random ones, and watch for target leakage through time: aggregates that include the current or future rows, or features recomputed with data that arrived after the prediction moment. Check the effect: with cyclical and lag features, the linear model's MAE fell from 14.8 to 9.6 rides.

Distances on the circle

T = 24. 23:00 → (sin, cos) = (−0.259, 0.966); 00:00 → (0, 1). Distance = √(0.259² + 0.034²) = 0.261 ≈ 2 sin(π/24). The integer encoding puts them 23 apart. 6:00 = (1, 0) and 18:00 = (−1, 0) are 2 apart, the maximum.

Key takeaway: Use sin and cos pairs with the right period for cyclical features, and build lag and rolling features from past data only.

How it works, step by step

Step 1 of 4
Data engineer

1. Standardise time

Parse timestamps, store UTC, convert to local time zones and handle daylight saving.

UTC in storage · local for hour-of-day
Key numbers at this step
Check
day-first vs month-first

When to use it & trade-offs

What it is

A timestamp is a rich source of features once it's decomposed. Calendar parts (hour, day of week, day of month, month, quarter, week of year, year, is-weekend, is-holiday, is-month-end) capture seasonality and business rhythm; elapsed-time features (days since signup, hours since last purchase, age of account) capture recency and tenure; lag and rolling-window features summarise recent history. Many calendar features are cyclical: hour 23 is next to hour 0, December is next to January. Encoding them as plain integers makes the model think 23 and 0 are far apart, so cyclical features are encoded with sine and cosine pairs: sin(2πt/T) and cos(2πt/T), which place the values on a circle where neighbours at the wrap-around stay close.

Why it matters: Time drives demand, fraud, traffic and churn, and models rarely discover calendar structure on their own from a raw timestamp. A good set of date-time features is often the single biggest accuracy gain on temporal problems. But time features also bring pitfalls: time zones and daylight saving, features built from the future (leakage), splits that ignore time order and holidays that move each year. Careful extraction and cyclical encoding make these signals usable and safe.

When to reach for it

  • Demand, traffic and fraud models
  • Any model with hour, weekday or seasonal effects
  • Forecasting with lag and rolling features

When to avoid or be careful

  • Using a raw hour integer in a linear model
  • Rolling features that include the current or future rows
  • Mixing time zones in the same feature

Encoding a periodic feature

Raw integer (0–23)
Best for: Tree-based models

Strengths: Simple; trees can split anywhere.

Watch out: Linear models see 23 and 0 as far apart.

One-hot
Best for: Small cycles with non-smooth effects (weekday)

Strengths: Flexible, no assumed shape.

Watch out: No neighbour information; more columns.

Sin and cos (Fourier)
Best for: Smooth periodic effects in linear and neural models

Strengths: Respects wrap-around; two columns.

Watch out: Less interpretable; may need several harmonics.

Interview signals & numbers to know

When this topic comes up

  • “Demand peaks at 6 pm”
  • sin and cos encoding
  • Lag features and rolling means
  • Daylight saving errors
  • Holiday effects

Benchmarks & rules of thumb

2 sin(π/24) = 0.261 -
distance between adjacent hours on the circle
24 · 7 · 12 · 365.25 -
periods for hour, weekday, month and day of year
14.8 → 9.6 -
MAE of a linear model before and after time features

Common mistakes & follow-ups

Common interview mistakes

  • Encoding only sin and losing the distinction between mirrored times.
  • Computing weekly aggregates over the full week when predicting mid-week.
  • Splitting train and test randomly on time-ordered data.

Likely interviewer follow-ups

  • Why encode hour with sine and cosine?
  • How do you create lag features without leakage?
  • How do you handle time zones in feature engineering?
Interview tip: Mention the chord distance (0.261 versus 23). It's a concrete argument for cyclical encoding.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Date-Time & Cyclical Feature Extraction with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Binning, Discretization & Interaction Features
Next topic
Feature Selection (Filter, Wrapper, Embedded)