Extração de características de data e hora
Os alunos decomporão colunas de data e hora em ano, mês, dia da semana e hora, além de codificações cíclicas de seno e cosseno que capturam a periodicidade.
Extração de características de data e hora é uma aula grátis de Machine Learning Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Machine Learning Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Machine Learning Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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.
Perguntas Frequentes
A aula “Extração de características de data e hora” é grátis?
Sim — o texto completo de “Extração de características de data e hora” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Machine Learning Academy, atualize para CoddyKit PRO. O curso de Machine Learning Academy inclui 4 aulas no total.
O que vou aprender em “Extração de características de data e hora”?
Os alunos decomporão colunas de data e hora em ano, mês, dia da semana e hora, além de codificações cíclicas de seno e cosseno que capturam a periodicidade. Você pratica Machine Learning Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Machine Learning Academy?
Nenhuma experiência prévia é necessária. Machine Learning Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “Extração de características de data e hora”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Machine Learning Academy?
Sim. Cada aula de Machine Learning Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Criação de novas características: transformações logarítmicas, agrupamento e interações
- Extração de características de data e hora
- Seleção de características: limite de variância e SelectKBest
- Eliminação recursiva de características com validação cruzada