Time-series analysis is one of Pandas' most powerful core capabilities. Built on NumPy's high-performance datetime64 and timedelta64 types, Pandas provides intuitive tools for parsing text timestamps, generating continuous date ranges, shifting intervals using calendar rules, downsampling frequencies, and calculating rolling window statistics. This pillar page serves as the master guide to the entire Pandas datetime ecosystem.
Pandas represents temporal data using four primary objects:
datetime.datetime).Q1 2026) or calendar month (2026-04).Use pd.to_datetime() to parse strings, Unix epoch numbers, or lists into Pandas Timestamps. Explicitly specify the format string to accelerate parsing and prevent ambiguity between US (MM/DD) and European (DD/MM) date conventions:
import pandas as pd
# Parse current timestamp
now_ts = pd.to_datetime("now")
print("Current Time:", now_ts)
# Parse custom formatted string
custom_ts = pd.to_datetime("12252026:233445", format="%m%d%Y:%H%M%S")
print("Parsed Custom Date:", custom_ts)
# Convert an entire DataFrame column to datetime64
df = pd.DataFrame({
"NAME": ["Ravi", "Raju", "Alex", "Ron"],
"dt_start": ["2026-01-15 08:30:00", "2026-02-20 14:15:00", "2026-03-10 18:45:00", "2026-04-05 09:00:00"]
})
df["dt_start"] = pd.to_datetime(df["dt_start"])
print(df.dtypes)
Similar to the .str accessor for text, the .dt accessor allows vectorized extraction of date components across Series without writing manual Python loops:
# Extract calendar parts
df["year"] = df["dt_start"].dt.year
df["month"] = df["dt_start"].dt.month
df["day_name"] = df["dt_start"].dt.day_name()
df["is_weekend"] = df["dt_start"].dt.dayofweek >= 5
print(df)
Generate continuous calendar or business sequences using pd.date_range():
# Daily sequence of 10 days
days = pd.date_range(start="2026-01-01", periods=10, freq="D")
# Business days only (skips Saturday & Sunday)
business_days = pd.date_range(start="2026-01-01", periods=10, freq="B")
# Hourly sequence with custom step
hourly = pd.date_range(start="2026-01-01", periods=6, freq="4h")
Perform precise calendar addition and subtraction without manual leap year or month length calculations:
# Adding fixed durations via Timedelta
df["dt_plus_7d"] = df["dt_start"] + pd.Timedelta(days=7)
# Shifting by calendar months via DateOffset
df["next_month"] = df["dt_start"] + pd.DateOffset(months=1)
When working with indexed time-series data, resample() aggregates observations into regular time buckets (similar to a temporal groupby), while rolling() calculates moving statistics:
# Set DatetimeIndex
df_ts = df.set_index("dt_start")
# Downsample to monthly total
monthly_summary = df_ts.resample("ME").count()
# Calculate 7-day rolling average
rolling_avg = df_ts["year"].rolling(window=7, min_periods=1).mean()
The table below lists all standard offset strings used with date_range(), period_range(), and resample():
| Offset Alias | Description | Offset Alias | Description |
|---|---|---|---|
B | Business day frequency | MS | Month start frequency |
C | Custom business day | SMS | Semi-month start (1st & 15th) |
D | Calendar day frequency | BMS | Business month start |
W | Weekly frequency | Q | Quarter end frequency |
M / ME | Month end frequency | BQS | Business quarter start |
SM | Semi-month end (15th & end) | Y / YE | Year end frequency |
BM | Business month end | YS | Year start frequency |
CBM | Custom business month end | h | Hourly frequency |
min | Minutely frequency | s | Secondly frequency |
ms | Milliseconds | us | Microseconds |
Deep-dive into each specialized operation and practice challenge in this topic cluster:
In business analytics, transaction records arrive at irregular timestamps. This workflow normalizes irregular orders into a continuous daily time series, aggregates revenue, and calculates a 7-day rolling trend:
import pandas as pd
import numpy as np
np.random.seed(42)
timestamps = pd.date_range(start="2026-01-01", periods=30, freq="D")
sales = np.random.normal(2500, 400, 30)
df_sales = pd.DataFrame({
"date": timestamps,
"daily_sales": np.round(sales, 2)
})
df_sales = df_sales.set_index("date")
# Weekly resampling
weekly = df_sales.resample("W").sum()
print("Weekly Resampled Revenue:\n", weekly.head(3))
assert len(df_sales) == 30
assert weekly["daily_sales"].sum() == df_sales["daily_sales"].sum()
Expected console output:
Weekly Resampled Revenue:
daily_sales
date
2026-01-04 11011.67
2026-01-11 18095.21
2026-01-18 15450.86
Given the following joining dates of 4 team members, perform these tasks:
hire_date strings to datetime.2026-10-11.pd.DateOffset(years=5).import pandas as pd
staff = pd.DataFrame({
"employee": ["Alice", "Bob", "Charlie", "Diana"],
"hire_date": ["2021-03-15", "2022-07-01", "2023-11-20", "2025-01-10"]
})
staff["hire_date"] = pd.to_datetime(staff["hire_date"])
ref_date = pd.to_datetime("2026-10-11")
staff["tenure_days"] = (ref_date - staff["hire_date"]).dt.days
staff["anniversary_5yr"] = staff["hire_date"] + pd.DateOffset(years=5)
print(staff)
assert staff["tenure_days"].max() > 1500
assert staff["anniversary_5yr"].iloc[0] == pd.Timestamp("2026-03-15")
Expected console output:
employee hire_date tenure_days anniversary_5yr
0 Alice 2021-03-15 2036 2026-03-15
1 Bob 2022-07-01 1563 2027-07-01
2 Charlie 2023-11-20 1056 2028-11-20
3 Diana 2025-01-10 639 2030-01-10
Open in Google Colab View on GitHub
Run all datetime parsing, offset shifts, resampling, and tenure calculations interactively in Google Colab. All sample datasets are embedded directly in the notebook.
Reference: Pandas Time Series / Date functionality documentation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.