Extracción de características de fecha y hora
Descompondrá las columnas datetime en año, mes, día de la semana y hora, además de codificaciones cíclicas de seno y coseno que capturen la periodicidad.
Extracción de características de fecha y hora es una lección gratuita de Machine Learning Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Machine Learning Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Machine Learning Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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)) # largeApplying 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.
Preguntas frecuentes
¿La lección «Extracción de características de fecha y hora» es gratis?
Sí — el texto completo de «Extracción de características de fecha y hora» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Machine Learning Academy, actualiza a CoddyKit PRO. El curso de Machine Learning Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Extracción de características de fecha y hora»?
Descompondrá las columnas datetime en año, mes, día de la semana y hora, además de codificaciones cíclicas de seno y coseno que capturen la periodicidad. Practicas Machine Learning Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Machine Learning Academy?
No se requiere experiencia previa. Machine Learning Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «Extracción de características de fecha y hora»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Machine Learning Academy?
Sí. Cada lección de Machine Learning Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Creación de nuevas características: transformaciones logarítmicas, discretización e interacciones
- Extracción de características de fecha y hora
- Selección de características: Variance Threshold y SelectKBest
- Eliminación recursiva de características con validación cruzada