All Parts of Pandas Datetime Functionality
Pandas offers one of the most complete and powerful toolsets for working with datetime data in Python. From loading and parsing to component extraction, timezone handling, arithmetic, rounding, resampling, rolling windows, and advanced transformations, the .dt accessor combined with pd.to_datetime, Timedelta, resample(), and rolling() covers virtually every time-based operation you will encounter.
TL;DR — Complete Pandas Datetime Toolkit
- Loading:
parse_dates,date_format,pd.to_datetime() - Components:
.dt.year,.dt.month,.dt.day_name(),.dt.hour - Timezone:
.dt.tz_localize(),.dt.tz_convert() - Arithmetic:
+/-withTimedelta - Rounding:
.dt.floor(),.dt.ceil(),.dt.round(),.dt.normalize() - Resampling & Rolling:
.resample(),.rolling() - Periods & Frequency:
.dt.to_period()
1. Loading & Parsing Datetimes
import pandas as pd
# Demo file so this example runs as-is (in your project this is your real export)
times = pd.date_range("2026-03-06 12:00", periods=40, freq="3h")
pd.DataFrame({
"order_id": range(1001, 1041),
"order_time": times.strftime("%Y-%m-%d %H:%M:%S"),
"order_date": times.strftime("%Y-%m-%d %H:%M:%S"),
"delivery_date": (times + pd.Timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S"),
"amount": [round(50 + 11.5 * k, 2) for k in range(40)],
}).to_csv("sales_data.csv", index=False)
df = pd.read_csv("sales_data.csv",
parse_dates=["order_date", "delivery_date"],
date_format="%Y-%m-%d %H:%M:%S") # naive; localized to UTC below
2. Component Extraction & Feature Engineering
df["year"] = df["order_date"].dt.year
df["month"] = df["order_date"].dt.month
df["day_name"] = df["order_date"].dt.day_name()
df["hour"] = df["order_date"].dt.hour
df["is_weekend"] = df["order_date"].dt.day_of_week.isin([5, 6])
3. Timezone Handling
df["order_date_utc"] = df["order_date"].dt.tz_localize("UTC")
df["order_date_ny"] = df["order_date_utc"].dt.tz_convert("America/New_York")
4. Arithmetic & Rounding
now = pd.Timestamp.now(tz="UTC")
df["hours_since_order"] = (now - df["order_date_utc"]).dt.total_seconds() / 3600
df["day_start"] = df["order_date"].dt.floor("D")
df["hour_rounded"] = df["order_date"].dt.round("h")
5. Resampling, Rolling & Periods
df = df.set_index("order_date_utc")
daily_sales = df.resample("D")["amount"].sum()
rolling_7d = df["amount"].rolling("7D").mean()
df["month_period"] = df.index.tz_convert(None).to_period("M") # periods carry no time zone
6. Best Practices in 2026
- Parse datetime columns as early as possible
- Store all internal timestamps in UTC
- Use the
.dtaccessor for all component and transformation operations - Perform arithmetic with
Timedeltaon timezone-aware data - Use
resample()androlling()for time-series analysis - Always test around DST transition dates
Periods, Timestamps and Timedeltas
pandas has three related datetime types. A Timestamp is one instant, a Timedelta is a length of time, and a Period is a whole span such as March 2026. Mixing them up is a common source of confusion: subtracting two Timestamps gives a Timedelta, while converting to a Period loses the time of day.
Periods do not carry time zones, so convert aware data to naive UTC first with tz_convert(None) before calling to_period. pandas would otherwise drop the zone and warn.
Periods are ideal for monthly or quarterly reports because each row clearly belongs to one span, no matter how many days that span has.
Worked Example: Monthly Report from Aware Timestamps
Aware timestamps are grouped into calendar months using periods.
import pandas as pd
ts = pd.Series(pd.to_datetime(["2026-01-31 23:30", "2026-02-01 00:30", "2026-02-15 12:00"]).tz_localize("UTC"))
amount = pd.Series([100, 40, 60])
month = ts.dt.tz_convert(None).dt.to_period("M")
print(amount.groupby(month).sum())
print(ts.iloc[1] - ts.iloc[0])
print(month.iloc[0].start_time, month.iloc[0].end_time)
January has 100 and February 100 in total. The two first timestamps are only one hour apart but fall in different months, and the Period shows the exact span of January.
Practical Tips
Choose the type that matches the question. Use Timestamps for events, Timedeltas for durations such as delivery times, and Periods for reporting spans such as months or quarters.
Converting between them is cheap, so it is better to convert explicitly than to force one type to do every job.
When sharing results, convert Periods to strings with astype(str), which gives readable labels such as 2026-01 in charts and exported files.
A short check such as print(type(x)) helps when a value's type is unclear.
Common Mistakes
- Calling to_period on aware data without removing the zone.
- Treating a Timedelta as a calendar month.
- Grouping by month number across several years.
- Forgetting that periods drop the time of day.
Quick Summary
- Timestamp is an instant, Timedelta a length.
- Period is a whole calendar span.
- Convert to naive UTC before to_period.
- Use periods for monthly reports.
Conclusion
Pandas datetime functionality is comprehensive and highly performant. In 2026, mastering the full range of operations — from parsing and component extraction to timezone handling, arithmetic, rounding, resampling, and rolling windows — allows you to turn raw timestamps into powerful, actionable insights with clean, vectorized code.
Next steps:
- Review your current datasets and apply the complete set of Pandas datetime operations to extract maximum value from your time-based data