Machine Learning Academy · Lezione

Estrazione di feature da date e orari

Imparerete a scomporre le colonne datetime in anno, mese, giorno della settimana e ora, oltre a creare codifiche cicliche seno/coseno che catturano la periodicità.

Lezione 2 di 413 passaggi

Estrazione di feature da date e orari è una lezione Machine Learning Academy gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Machine Learning Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Machine Learning Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Why Raw Timestamps Are Useless

A raw Unix timestamp like 1718784000 or a datetime string like '2024-06-19 14:30:00' contains rich information — the hour of day, day of week, month of year — but a model cannot access that information from the raw value. A linear model sees the timestamp as a single large integer and can only learn that later timestamps predict higher/lower targets, missing all periodic patterns. Feature extraction decomposes the timestamp into meaningful numeric components that models can directly use.

Parsing Datetime Columns with Pandas

Always parse date/time strings to pd.Timestamp or datetime64 dtype using pd.to_datetime() before extracting features. Once parsed, Pandas provides a .dt accessor with dozens of attributes: .dt.year, .dt.month, .dt.day, .dt.hour, .dt.minute, .dt.dayofweek (0=Monday), .dt.dayofyear, .dt.quarter, .dt.is_weekend, and more. Each attribute becomes a new integer column in your feature matrix.

import pandas as pd

dates = pd.Series(['2024-01-15 08:30:00', '2024-06-21 17:45:00', '2024-12-25 12:00:00'])
dts = pd.to_datetime(dates)

df = pd.DataFrame({
    'year': dts.dt.year,
    'month': dts.dt.month,
    'day': dts.dt.day,
    'hour': dts.dt.hour,
    'dayofweek': dts.dt.dayofweek,  # 0=Mon, 6=Sun
    'quarter': dts.dt.quarter,
    'is_weekend': (dts.dt.dayofweek >= 5).astype(int)
})
print(df.to_string())

The Problem with Raw Cyclical Features

Hours 23 and 0 are adjacent (one hour apart) but numerically far apart (23 units). If you encode hour as an integer 0-23, a linear model cannot learn that midnight patterns are similar to 11pm patterns. The same applies to months (December and January are adjacent), day-of-week (Sunday=6 and Monday=0), and any other cyclical quantity. Treating these as raw integers creates an artificial discontinuity at the cycle boundary that models have to work around.

Cyclical Encoding with Sine and Cosine

The solution is to encode cyclical features as sine and cosine pairs. For a variable ranging from 0 to T-1, encode it as: sin(2π × value / T) and cos(2π × value / T). This maps the cycle onto a circle in 2D space. Hour 23 and hour 0 are now adjacent points on the circle, so their Euclidean distance is small. Any model that computes distances or linear combinations can now capture cyclical patterns correctly using both the sin and cos components together.

import numpy as np
import pandas as pd

hours = np.arange(24)
df = pd.DataFrame({'hour': hours})
df['hour_sin'] = np.sin(2 * np.pi * df['hour'] / 24)
df['hour_cos'] = np.cos(2 * np.pi * df['hour'] / 24)

# Distance between hour 23 and hour 0 on the circle
def circle_dist(h1, h2):
    s1, c1 = df.loc[df['hour'] == h1, ['hour_sin', 'hour_cos']].values[0]
    s2, c2 = df.loc[df['hour'] == h2, ['hour_sin', 'hour_cos']].values[0]
    return np.sqrt((s1-s2)**2 + (c1-c2)**2)

print('Distance 23 to 0:', round(circle_dist(23, 0), 4))  # small
print('Distance 0 to 12:', round(circle_dist(0, 12), 4))  # large

Applying Cyclical Encoding to Multiple Features

The cyclical encoding pattern generalises to any periodic feature: month (T=12), day of week (T=7), hour (T=24), minute (T=60), day of year (T=365). Each cyclical feature generates two new features (sin and cos). For tree-based models, raw integer encoding often works fine because trees split on thresholds and can capture cyclical patterns through multiple splits. But for linear models, neural networks, and distance-based algorithms, cyclical encoding is important.

import numpy as np
import pandas as pd

def cyclical_encode(df, col, period):
    df[col + '_sin'] = np.sin(2 * np.pi * df[col] / period)
    df[col + '_cos'] = np.cos(2 * np.pi * df[col] / period)
    return df

df = pd.DataFrame({'hour': [8, 12, 20, 23], 'month': [1, 6, 11, 12], 'dow': [0, 2, 4, 6]})
df = cyclical_encode(df, 'hour', 24)
df = cyclical_encode(df, 'month', 12)
df = cyclical_encode(df, 'dow', 7)
print(df[['hour', 'hour_sin', 'hour_cos', 'month', 'month_sin', 'month_cos']].round(3))

Time Since Reference: Relative Timestamps

Instead of extracting calendar components, sometimes what matters is time elapsed since an event: days since last purchase, hours since system restart, months since account creation. These relative duration features capture recency effects that absolute calendar features miss. Compute them as simple differences: (now - event_date).dt.days or (now - event_date).dt.total_seconds(). Recency features are especially valuable in customer behaviour models (churn, LTV) and predictive maintenance.

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'last_purchase': pd.to_datetime(['2024-01-10', '2024-05-20', '2024-06-15']),
    'signup_date': pd.to_datetime(['2023-01-01', '2023-06-15', '2024-01-01'])
})
reference = pd.Timestamp('2024-06-19')
df['days_since_purchase'] = (reference - df['last_purchase']).dt.days
df['account_age_days'] = (reference - df['signup_date']).dt.days
print(df[['days_since_purchase', 'account_age_days']])

Is Weekend and Business Hours Flags

Boolean indicator features derived from timestamps are simple but often powerful. is_weekend, is_business_hours, is_holiday, is_month_end — these create clear binary splits that tree models can exploit in a single split. Linear models also benefit because these flags create distinct intercept adjustments. Adding a public holiday flag can be especially impactful for retail sales, traffic, and energy consumption models where holidays cause systematic demand shifts.

import pandas as pd

dates = pd.to_datetime(['2024-06-17', '2024-06-19', '2024-06-21', '2024-06-22', '2024-12-25'])
df = pd.DataFrame({'date': dates})
df['is_weekend'] = (df['date'].dt.dayofweek >= 5).astype(int)
df['is_month_end'] = df['date'].dt.is_month_end.astype(int)
df['is_quarter_end'] = df['date'].dt.is_quarter_end.astype(int)
df['week_of_year'] = df['date'].dt.isocalendar().week.astype(int)
print(df.to_string())

Lag Features and Rolling Statistics

For time-series data, the past values of the target variable are often among the best predictors. Lag features shift the target by N timesteps: df['target_lag1'] = df['target'].shift(1) creates a feature equal to yesterday's target. Rolling statistics summarise recent history: df['rolling_mean_7'] = df['target'].rolling(7).mean() gives the 7-day moving average. These features encode temporal momentum and seasonality that calendar features alone cannot capture.

import pandas as pd
import numpy as np

np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=10)
sales = np.array([100, 120, 95, 130, 110, 145, 160, 155, 170, 180])
df = pd.DataFrame({'date': dates, 'sales': sales})

df['lag_1'] = df['sales'].shift(1)
df['lag_7'] = df['sales'].shift(7)
df['rolling_mean_3'] = df['sales'].rolling(3).mean()
df['rolling_std_3'] = df['sales'].rolling(3).std()
print(df.to_string())

Combining Date Features in a Pipeline

To use date feature extraction inside a scikit-learn Pipeline without leakage, create a custom transformer using BaseEstimator and TransformerMixin. This ensures date features are computed consistently and reproducibly within each fold of cross-validation. For lag and rolling features, be extra careful — rolling statistics computed across the full dataset (including future test data) will leak information. Always compute lag/rolling features only up to the training cutoff date.

import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin

class DateFeatureExtractor(BaseEstimator, TransformerMixin):
    def fit(self, X, y=None):
        return self
    def transform(self, X):
        X = X.copy()
        dt = pd.to_datetime(X['date'])
        X['hour'] = dt.dt.hour
        X['dayofweek'] = dt.dt.dayofweek
        X['month'] = dt.dt.month
        X['hour_sin'] = np.sin(2 * np.pi * X['hour'] / 24)
        X['hour_cos'] = np.cos(2 * np.pi * X['hour'] / 24)
        X = X.drop('date', axis=1)
        return X

df = pd.DataFrame({'date': ['2024-06-19 08:00', '2024-06-20 15:30'], 'value': [10, 20]})
print(DateFeatureExtractor().fit_transform(df))

Choosing Features Based on Domain Knowledge

Effective datetime feature engineering requires understanding which temporal patterns matter for your problem. For ride-sharing demand: hour-of-day and day-of-week are critical. For retail sales: day-of-week, week-of-year, proximity to holidays, and year-over-year trend. For network intrusion detection: time-since-last-event and burst rate. For energy consumption: hour, day, and temperature interactions. Always start by plotting the target against each temporal component to identify visible periodic patterns before engineering features.

Handling Multiple Time Zones

When your dataset spans multiple time zones, always convert timestamps to a single reference timezone before feature extraction. Using UTC as the canonical timezone is standard practice. After extracting features, you can re-apply local-time offsets if local patterns matter (e.g., hour of day in customer's local time is more predictive than UTC hour for user behaviour modelling). The Pandas dt.tz_localize() and dt.tz_convert() methods handle timezone conversion cleanly.

import pandas as pd

# Timestamps in mixed timezones
timestamps = ['2024-06-19 08:00:00-05:00',  # US/Chicago
              '2024-06-19 14:00:00+01:00',   # Europe/London
              '2024-06-19 22:00:00+09:00']   # Asia/Tokyo
df = pd.DataFrame({'ts': pd.to_datetime(timestamps, utc=True)})
df['utc_hour'] = df['ts'].dt.hour  # all in UTC after conversion
df['ts_ny'] = df['ts'].dt.tz_convert('America/New_York')
df['ny_hour'] = df['ts_ny'].dt.hour  # local time hour
print(df[['utc_hour', 'ny_hour']])

Quick Check

Test your understanding of Date and Time feature extraction from this lesson.

Lesson Recap

In this lesson you learned: raw timestamps must be decomposed into meaningful components before use as features, cyclical features like hour and month require sine/cosine encoding to avoid boundary discontinuities, and lag and rolling features encode temporal patterns for time-series prediction tasks. Next up we explore Feature Selection with Variance Threshold and SelectKBest to discard uninformative features.

Gratis per iniziare

Impara Python con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
30
Lezioni
120

Domande Frequenti

La lezione «Estrazione di feature da date e orari» è gratuita?

Sì — il testo completo di «Estrazione di feature da date e orari» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Machine Learning Academy, passa a CoddyKit PRO. Il corso Machine Learning Academy include 4 lezioni in totale.

Cosa imparerò in «Estrazione di feature da date e orari»?

Imparerete a scomporre le colonne datetime in anno, mese, giorno della settimana e ora, oltre a creare codifiche cicliche seno/coseno che catturano la periodicità. Eserciti Machine Learning Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Machine Learning Academy?

Non è richiesta alcuna esperienza precedente. Machine Learning Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.

Quanto tempo richiede la lezione «Estrazione di feature da date e orari»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Machine Learning Academy?

Sì. Ogni lezione Machine Learning Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Creare nuove feature: trasformazioni logaritmiche, binning e interazioni
  2. Estrazione di feature da date e orari
  3. Selezione delle feature: Variance Threshold e SelectKBest
  4. Eliminazione ricorsiva delle feature con cross-validation
← Torna a Machine Learning Academy