Date & Time Manipulation
Parse timestamps, timezone-aware ops, resampling, and feature extraction from datetimes.
In plain words
Turn text into real dates, pull out parts like month and weekday, fix time zones, and total things by day, week or month.
Think of it like…
A wall of clocks in different cities: before comparing events you have to say which clock each time came from and convert them to one, and when you total by day you must say whose day you mean.
Where you’ve seen it
A retailer's orders are stored in UTC, but the business reports by Indian Standard Time. An order at 2026-11-04 19:30 UTC is 01:00 on 5 November in IST, so grouping by the UTC date puts late-evening Indian orders on the wrong day and makes daily sales look 4 percent off. Converting with tz_convert("Asia/Kolkata") before .dt.date fixes the daily report and aligns it with finance.
Words you’ll hear
- datetime64[ns] / Timestamp
- Pandas' native date-time type and its scalar.
- .dt accessor
- Extract parts and format dates from a datetime Series.
- Timezone-aware
- A timestamp carrying a zone, such as UTC or Asia/Kolkata; naive timestamps have none.
- resample
- Group a time-indexed Series or DataFrame into fixed frequency buckets.
Visual diagram
Theory & deep dive
Parsing, parts and arithmetic
Parse with pd.to_datetime(df["date"], format="%d/%m/%Y", errors="coerce") and count the resulting NaT; pass dayfirst=True only when you know the convention, and utc=True when strings carry offsets. Better still, parse at load time with read_csv(parse_dates=[...]). Then use .dt: df.date.dt.year, .dt.month, .dt.dayofweek (Monday = 0), .dt.hour, .dt.is_month_end, .dt.normalize() for midnight, .dt.to_period("M") for month periods and .dt.strftime("%b %Y") for labels.
Subtracting two datetimes gives a Timedelta: (df.delivered - df.ordered).dt.days or .dt.total_seconds() / 3600 for hours. Add durations with pd.Timedelta(days=7) and calendar offsets with pd.DateOffset(months=1), which respects month lengths. Useful feature ideas: weekday and hour, is_weekend, days since the customer's last order (groupby("customer").date.diff()), days to a holiday, and cyclical encodings (sine and cosine of the hour) for models.
df["delivery_hours"] = (df["delivered_at"] - df["ordered_at"]).dt.total_seconds() / 3600 gives a numeric feature; filter delivery_hours < 0 to catch timestamp errors.
Time zones and resampling
Store and exchange timestamps in UTC. A naive timestamp is localised with s.dt.tz_localize("UTC") (declaring what zone it's already in) and then converted for reporting with s.dt.tz_convert("Asia/Kolkata"); mixing up localise (label) and convert (change the clock time) is a classic error. Daylight-saving changes can create missing or repeated local times, which tz_localize can handle with ambiguous= and nonexistent= arguments. Compare and group in a single zone.
To aggregate over time, set a datetime index and call resample: df.set_index("order_ts").resample("D")["amount"].sum() for daily totals, "W-MON" for weeks, "MS" for month-start. Days with no orders appear as 0 for sums or NaN for means, so reindex or fill as needed. Beware of incomplete final periods (a half-finished month will look like a drop). rolling("7D").mean() gives a 7-day moving average over time-based windows, shift(1) makes lag features, and pct_change(7) gives week-over-week change.
daily = (orders.assign(ts=orders.ts.dt.tz_convert("Asia/Kolkata")).set_index("ts").resample("D").amount.sum()); daily.rolling(7).mean() computes sales per local day and smooths them over a week.
How it works, step by step
Step 1 of 41. Parse explicitly
Use format= or parse_dates, coerce failures to NaT and count them.
- Check
- NaT count
When to use it & trade-offs
What it is
Pandas represents timestamps as datetime64 values. pd.to_datetime parses text (with an explicit format= when it's ambiguous), the .dt accessor extracts parts (year, month, dayofweek, hour) and does date arithmetic, time zones are attached with tz_localize and converted with tz_convert, and resample aggregates a time-indexed series into regular buckets (daily, weekly, monthly). Timedelta represents durations, and rolling and shift compute moving windows and lags.
Why it matters: Almost every dataset has time: orders, sessions, sensor readings. Date handling is also where silent errors hide: day/month swaps, UTC vs local midnight shifting a sale into the wrong day, daylight-saving gaps, and monthly totals that include a partial month. Good time features (day of week, hour, days since last purchase) are often a model's most predictive inputs.
When to reach for it
- Daily, weekly and monthly reporting
- Lag, recency and seasonality features
- Delivery and session durations
When to avoid or be careful
- Auto-detecting ambiguous date formats
- Grouping by UTC dates for a local-time report
- Comparing the incomplete current month with full months
Working with dates
Strengths: Trivial to load.
Watch out: No arithmetic; sorting and grouping can be wrong.
Strengths: Vectorised, expressive, zone-aware.
Watch out: Requires careful parsing and zone handling.
Strengths: Represents spans; clean monthly keys.
Watch out: Less flexible for exact timestamps.
Interview signals & numbers to know
When this topic comes up
- “Daily sales look off”
- “Convert timestamps to local time”
- “Create time-based features”
- Resampling and rolling windows
- Daylight saving
Benchmarks & rules of thumb
- 0
- dt.dayofweek value for Monday
- UTC
- recommended storage zone
- NaT
- pandas' missing datetime
Common mistakes & follow-ups
Common interview mistakes
- Using
tz_localizewhentz_convertwas needed, labelling times with the wrong zone instead of converting. - Reporting a partial current month as a sales decline.
- Parsing "03/11/2026" with the wrong day/month convention for half the dataset.
Likely interviewer follow-ups
- What's the difference between tz_localize and tz_convert?
- How would you build a days-since-last-purchase feature?
- How do you compute a 7-day moving average?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Date & Time Manipulation with data science interview Q&A and hands-on practice.