Python for Data Analytics & AutomationLesson 22 of 41
Lesson 22 of 41

DateTime Operations, Parsing, Timezone Offsets & .dt Accessor

Overview & Learning Objectives

Temporal data is at the heart of trend analysis, seasonality detection, cohort tracking, and churn calculations. Raw date columns frequently arrive as dirty, mixed-format string strings. Pandas converts raw text into microsecond-precision `datetime64[ns]` objects, providing the `.dt` accessor to extract calendar attributes and calculate exact durations.

  • Convert dirty string timestamps into native `datetime64[ns]` using `pd.to_datetime(..., errors="coerce")`.
  • Extract temporal components (year, month, quarter, day of week, hour) using the `.dt` accessor.
  • Perform duration arithmetic using `pd.Timedelta` and compute delivery lead times.
  • Filter records using datetime string indexing and date range slicing.

Industry Standard

Standard: Analytics infrastructure at Zepto and Blinkit parses all order timestamps with UTC timezone localization before converting to Indian Standard Time (`Asia/Kolkata`) for accurate peak-hour operational reporting.

Real-World Example: ScoopCraft Peak Hours & Delivery SLA Analytics

ScoopCraft analyzes POS timestamps to detect evening order spikes and monitor kitchen prep durations.

Order IDOrder TimestampDispatch TimeHour of DayPrep Duration (mins)
ORD_7012026-06-15 14:22:102026-06-15 14:34:1014 (Afternoon)12.0 mins
ORD_7022026-06-15 19:45:002026-06-15 20:01:3019 (Peak Evening)16.5 mins
ORD_7032026-06-15 20:10:152026-06-15 20:21:4520 (Peak Evening)11.5 mins
ORD_7042026-06-15 21:30:002026-06-15 21:42:0021 (Night)12.0 mins

Syntax & Core Code Implementation

import pandas as pd

# 1. Parsing mixed string timestamps
raw_dates = ["15-06-2026 14:22:10", "2026/06/15 19:45:00", "invalid_date"]
dt_series = pd.to_datetime(raw_dates, errors="coerce", format="mixed")

# 2. Extracting calendar components (.dt accessor)
df = pd.DataFrame({"order_time": dt_series})
df["year"] = df["order_time"].dt.year
df["month_name"] = df["order_time"].dt.month_name()
df["day_name"] = df["order_time"].dt.day_name()
df["hour"] = df["order_time"].dt.hour
df["is_weekend"] = df["order_time"].dt.dayofweek >= 5

# 3. Timedelta duration math
df["dispatch_time"] = df["order_time"] + pd.Timedelta(minutes=15)
df["duration_mins"] = (df["dispatch_time"] - df["order_time"]).dt.total_seconds() / 60.0

Parameters & Arguments Breakdown

  • pd.to_datetime(arg, errors="coerce"): Parses timestamps. `errors="coerce"` turns invalid unparseable strings into NaT (Not-a-Time) instead of crashing.
  • s.dt.year / month / day: Extracts integer year, month (1-12), or day (1-31).
  • s.dt.day_name(): Returns day of the week as text string ("Monday", "Tuesday", etc.).
  • pd.Timedelta: Represents a duration of time (e.g., `pd.Timedelta(days=1, hours=3)`).

Sample Walkthrough (Q&A)

Question: What is the difference between `(t2 - t1).dt.seconds` and `(t2 - t1).dt.total_seconds()`?

Code Pattern: delta.dt.seconds vs delta.dt.total_seconds()

Result: `.seconds` returns the seconds remainder MODULO 1 day (0 to 86399); `.total_seconds()` returns the true total elapsed duration.

Explanation: If a duration is 1 day and 2 hours, `.seconds` returns 7200 (dropping the 24 hours entirely!). Always use `.total_seconds()` for duration metrics.

Common Mistakes & Limitations

  • Using `(t2 - t1).dt.seconds` to measure order turnaround times that exceed 24 hours, causing severe underreporting of delayed orders.
  • Not using `errors="coerce"`, which causes entire batch pipeline failures if even a single corrupt date string appears in millions of rows.

Keyboard Shortcuts (Jupyter & VS Code)

ActionWindowsMac
Quick Daily Resample & Aggregationdf.resample("D", on="date").sum()df.resample("D", on="date").sum()

Pro Tips & Modern Best Practices

  • Set `parse_dates=["col_name"]` directly inside `pd.read_csv()` to parse timestamps at C-speed during file ingestion.
  • Use `pd.Grouper(freq="ME")` inside `df.groupby()` for dynamic monthly/quarterly grouping.