machine learning
data pre-processing
date variables
feature engineering
data handling

How to handle date variable in machine learning data pre-processing

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Date columns often look simple, but they hide useful structure such as trend, seasonality, recency, and business-cycle effects. Most machine learning models cannot learn directly from raw date strings, so you need to convert those values into numeric features that preserve the patterns you care about.

Parse Dates into a Reliable Datetime Type

The first step is to parse the column consistently and deal with invalid values. In Python, pandas.to_datetime is the standard starting point.

python
1import pandas as pd
2
3df = pd.DataFrame(
4    {
5        "signup_date": ["2024-01-05", "2024-02-18", "2024-03-03", None],
6        "revenue": [120.0, 95.0, 142.0, 80.0],
7    }
8)
9
10df["signup_date"] = pd.to_datetime(df["signup_date"], errors="coerce", utc=True)
11print(df)

Using errors="coerce" turns invalid dates into missing values instead of crashing the pipeline. Adding utc=True is useful when your source data comes from different systems and might otherwise mix time zones.

Derive Calendar Features

Once the column is a datetime type, extract pieces that may matter for prediction. Common examples include year, month, day of week, quarter, and whether the date falls on a weekend.

python
1df["signup_year"] = df["signup_date"].dt.year
2df["signup_month"] = df["signup_date"].dt.month
3df["signup_dayofweek"] = df["signup_date"].dt.dayofweek
4df["signup_quarter"] = df["signup_date"].dt.quarter
5df["is_weekend"] = df["signup_dayofweek"].isin([5, 6]).astype(int)
6
7print(df[[
8    "signup_year",
9    "signup_month",
10    "signup_dayofweek",
11    "signup_quarter",
12    "is_weekend",
13]])

These features let the model learn patterns such as "weekend customers buy less" or "quarter four behaves differently from quarter two." The right set depends on the domain. Billing data may care about day-of-month, while retail data often benefits from month and holiday proximity.

Capture Recency and Cycles

Calendar integers alone can be misleading. For example, month 12 and month 1 are adjacent in time, but a model that sees them as plain integers may treat them as far apart. For repeating cycles, encode them in a circular form.

python
1import numpy as np
2
3df["month_sin"] = np.sin(2 * np.pi * df["signup_month"] / 12)
4df["month_cos"] = np.cos(2 * np.pi * df["signup_month"] / 12)
5
6reference_date = pd.Timestamp("2024-04-01", tz="UTC")
7df["days_since_signup"] = (reference_date - df["signup_date"]).dt.days
8
9print(df[["month_sin", "month_cos", "days_since_signup"]])

The sine and cosine pair helps the model understand that December and January are neighbors. The days_since_signup feature captures recency, which is often more useful than the raw timestamp.

Build the Features into a Training Pipeline

After feature extraction, decide whether to keep or drop the original datetime column. Many workflows drop it once all numeric features are created.

python
1feature_columns = [
2    "signup_year",
3    "signup_month",
4    "signup_dayofweek",
5    "signup_quarter",
6    "is_weekend",
7    "month_sin",
8    "month_cos",
9    "days_since_signup",
10]
11
12model_df = df[feature_columns + ["revenue"]].dropna()
13print(model_df)

If you are using scikit-learn, perform these transformations inside a preprocessing pipeline or a reproducible feature-generation step. That prevents training and inference from drifting apart.

Common Pitfalls

One common error is treating dates as plain strings or label-encoded categories. That destroys the temporal meaning and usually gives the model a noisy representation.

Another problem is leakage. If you compute days_since_signup relative to a date that occurs after the prediction time, you may accidentally give the model future information. Always define features using information available at prediction time.

Time zones also cause subtle bugs. If one source is in local time and another is UTC, day boundaries can shift, which changes weekday and hour-based features. Normalize first, then extract components.

Finally, use time-aware train and validation splits when the problem is temporal. A random split can make the model look better than it really is because it lets future patterns leak into training.

Summary

  • Convert raw date strings to a real datetime type before feature engineering.
  • Extract calendar parts such as month, quarter, and day of week when they match the business problem.
  • Use cyclical encoding for repeating values such as month or hour.
  • Create recency features when elapsed time matters more than the original timestamp.
  • Guard against leakage, mixed time zones, and random splits in time-based problems.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.