pythonbeginner
Pandas Datetime Component Extraction
Extract year, month, day, hour, day-of-week and other components from a datetime column.
pythonPress ⌘/Ctrl + Shift + C to copy
import pandas as pd
df = pd.DataFrame({'ts': pd.date_range('2024-01-01', periods=10, freq='6h')})
df['year'] = df['ts'].dt.year
df['month'] = df['ts'].dt.month
df['day'] = df['ts'].dt.day
df['hour'] = df['ts'].dt.hour
df['weekday'] = df['ts'].dt.day_name()
df['is_weekend'] = df['ts'].dt.dayofweek >= 5
df['quarter'] = df['ts'].dt.quarter
print(df)Use Cases
- time-based features
- temporal analysis
- ETL preprocessing
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
Pandas Categorical Encoding for ML
One-hot encode, label encode, and ordinal encode categorical columns using pandas and scikit-learn.
Best for: ML preprocessing
#pandas#encoding
pythonintermediate
Pandas IntervalIndex for Binning
Use IntervalIndex and pd.cut to bin continuous variables into labelled categories.
Best for: grading systems
#pandas#binning
pythonintermediate
Timezone-Aware Timestamps in pandas
Convert naive timestamps to timezone-aware, handle DST transitions, and localise to UTC.
Best for: global event logs
#pandas#datetime
pythonintermediate
Pandas GroupBy Transform Patterns
Use groupby().transform() to compute group-level statistics and broadcast them back to row level.
Best for: feature engineering
#pandas#groupby