Formatting Datetime in Python

Regular Expressions Mar 20, 2026

Formatting Datetime in Python

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

# Create a small demo file so this example runs as-is
# (in your project, sales_data.csv is your real export)
import numpy as np
rng = np.random.default_rng(42)
n = 60
pd.DataFrame({
    "order_id": range(1001, 1001 + n),
    "order_date": pd.date_range("2026-01-01", periods=n, freq="3D"),
    "customer_id": rng.integers(101, 121, n),
    "customer_name": rng.choice([" ana", "ben ", "chen", "dana"], n),
    "product_id": rng.integers(1, 9, n),
    "region": rng.choice(["North", "South", "East", "West"], n),
    "category": rng.choice(["Electronics", "Computers", "Books", "Home"], n),
    "payment_method": rng.choice(["card", "cash", "wallet"], n),
    "segment": rng.choice(["consumer", "business"], n),
    "quantity": rng.integers(1, 6, n),
    "amount": rng.uniform(50, 2500, n).round(2),
    "discount": rng.choice([0.0, 0.05, 0.1, 0.2], n),
}).assign(
    price=lambda d: (d["amount"] / d["quantity"]).round(2),
    profit=lambda d: (d["amount"] * rng.uniform(0.05, 0.3, n)).round(2),
).assign(
    ship_date=lambda d: d["order_date"] + pd.Timedelta(days=2),
    status=lambda d: np.where(d["amount"] > 2000, "priority", "standard"),
).to_csv("sales_data.csv", index=False)

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

strftime and strptime Are Mirror Images

strftime turns a datetime into text and strptime turns text into a datetime, using the same codes: %Y for a four-digit year, %m for month, %d for day, %H and %M for hours and minutes. A format that works for one direction works for the other.

Codes such as %B (month name) and %A (weekday name) depend on the locale, so output can change on servers with a different language setting. ISO 8601 text from isoformat() avoids that problem and sorts correctly as plain text.

Datetimes also support format specifications inside f-strings, so f"{dt:%Y-%m-%d}" is a short alternative to strftime.

Worked Example: Round-Tripping a Date

A date is formatted, parsed back and compared with the original.

from datetime import datetime

dt = datetime(2026, 3, 19, 14, 5)
fmt = "%d/%m/%Y %H:%M"

text = dt.strftime(fmt)
back = datetime.strptime(text, fmt)
print(text, back == dt)
print(dt.isoformat(), f"{dt:%Y-%m-%d}")
print(sorted(["2026-03-19", "2025-12-01", "2026-01-05"]))

The round trip returns the same datetime because both directions use one format. ISO dates sort correctly as text, which is why they are the best choice for file names and keys.

Practical Tips

Use one date format for every file name and log line in a project, and prefer ISO 8601 so the files sort in time order.

Common Mistakes

  • Using %M (minutes) when %m (month) is meant.
  • Relying on locale-dependent names in data files.
  • Storing dates in day-first text that sorts incorrectly.
  • Parsing with a format different from the one used to write.

Quick Summary

  • strftime formats; strptime parses.
  • Both use the same codes.
  • ISO 8601 sorts as text.
  • f-strings accept date formats.

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()

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices