Formatting Datetime in Python – Complete Guide for Data Science 2026
Formatting datetime objects into readable or machine-friendly strings is a daily task in data science. Whether you need clean log entries, report-ready dates, filename-safe timestamps, or strings ready for Regular Expression matching, mastering datetime formatting ensures your output is consistent, professional, and easy to work with.
TL;DR — Key Datetime Formatting Methods
.strftime(format)→ full control with format codes.isoformat()→ standard machine-readable ISO 8601- pandas
.dt.strftime()→ vectorized formatting on DataFrames - Always format timezone-aware objects for accuracy
1. Basic Datetime Formatting
from datetime import datetime
from zoneinfo import ZoneInfo
now = datetime.now(ZoneInfo("UTC"))
print(now.strftime("%Y-%m-%d")) # 2026-03-20
print(now.strftime("%A, %B %d, %Y at %H:%M:%S")) # Friday, March 20, 2026 at 14:30:25
print(now.strftime("%d/%m/%Y %I:%M %p")) # 20/03/2026 02:30 PM
print(now.isoformat()) # 2026-03-20T14:30:25.123456+00:00
2. pandas – Vectorized Datetime Formatting
import pandas as pd
df = pd.read_csv("sales_data.csv", parse_dates=["order_date"])
df["report_date"] = df["order_date"].dt.strftime("%B %Y") # March 2026
df["file_safe"] = df["order_date"].dt.strftime("%Y%m%d") # 20260320
df["full_human"] = df["order_date"].dt.strftime("%A, %B %d, %Y")
3. Real-World Data Science Examples
# Example 1: Generate daily report filenames
today_str = datetime.now(ZoneInfo("UTC")).strftime("%Y%m%d")
filename = f"daily_report_{today_str}.csv"
# Example 2: Create consistent log timestamps
log_time = datetime.now(ZoneInfo("UTC")).strftime("%Y-%m-%d %H:%M:%S UTC")
print(f"[{log_time}] Model training completed")
# Example 3: Build time-based categorical features
df["month_year"] = df["order_date"].dt.strftime("%Y-%m")
df["day_name"] = df["order_date"].dt.strftime("%A")
4. Best Practices in 2026
- Use
strftime()for custom human-readable formats - Use
isoformat()for machine-readable output (APIs, JSON, storage) - Apply pandas
.dt.strftime()for bulk formatting on DataFrames - Always format timezone-aware datetimes consistently
- Define common format strings as constants for project-wide consistency
Conclusion
Formatting datetime objects is a critical skill that bridges raw timestamps and usable output in data science. In 2026, combining strftime(), isoformat(), and pandas vectorized methods ensures your logs, reports, file names, and features are clean, consistent, and professional. These techniques also prepare your formatted strings perfectly for downstream Regular Expression processing.
Next steps:
- Add formatted datetime string columns to your current datasets using
strftime()or.dt.strftime()