Pandas
1 min read
Updated 4 Aug 2026
14. DateTime
df['date'] = pd.todatetime(df['date']) # parse strings
df['date'] = pd.to_datetime(df['date']) # parse strings
pd.date_range('2024-01-01', periods=5, freq='D') # daily range
pd.Timedelta(days=7)
# dt accessor
df['date'].dt.year
df['date'].dt.month
df['date'].dt.day_name()
df['date'].dt.dayofweek # Mon=0
df['date'].dt.quarter
# set datetime index for resampling
df = df.set_index('date')
df['sales'].resample('M').sum() # monthly totals
df['sales'].resample('W').mean() # weekly average
# timezones
df['date'].dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
| Tool | Purpose |
|---|---|
to_datetime |
parse strings/ints to datetime |
date_range |
generate regular date sequences |
Timedelta |
durations for date arithmetic |
.dt accessor |
extract parts (year, month, weekday) |
resample |
group time series by frequency |
Common frequency strings: D day, W week, M month-end, MS month-start, Q quarter, Y year, H hour, T/min minute.
🚀 Best Practice: Set the datetime column as the index before
resampleorrolling. Alwaysparse_datesat read time.
⭐ Interview Question: How to aggregate daily data to monthly? Set datetime index, then
df.resample('M').sum()(ormean,last, etc.).