날짜 및 시간 특성 추출
학습자는 datetime 열을 연도, 월, 요일, 시간 및 주기성을 포착하는 사인·코사인 주기 인코딩으로 분해합니다.
날짜 및 시간 특성 추출은(는) CoddyKit의 무료 Machine Learning Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Machine Learning Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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.
자주 묻는 질문
“날짜 및 시간 특성 추출” 강의는 무료인가요?
네 — “날짜 및 시간 특성 추출” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Machine Learning Academy 강의 전체를 잠금 해제할 수 있습니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“날짜 및 시간 특성 추출”에서 뭘 배우나요?
학습자는 datetime 열을 연도, 월, 요일, 시간 및 주기성을 포착하는 사인·코사인 주기 인코딩으로 분해합니다. 브라우저에서 직접 실행하는 실습 코드로 Machine Learning Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Machine Learning Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Machine Learning Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“날짜 및 시간 특성 추출” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Machine Learning Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Machine Learning Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.