strftime Format Codes in Python

Dates And Time Mar 19, 2026

strftime Format Codes in Python

The strftime() method is the most powerful and flexible way to turn Python date and datetime objects into formatted strings. In data science, it is used constantly for generating readable reports, creating file names, building log entries, and preparing features for modeling. Mastering format codes lets you control exactly how dates and times appear in your outputs.

TL;DR — Most Useful strftime Codes

  • %Y → 4-digit year (2026)
  • %m → 2-digit month (03)
  • %d → 2-digit day (19)
  • %A → Full weekday name (Thursday)
  • %H:%M:%S → Time in 24-hour format
  • %Y-%m-%d → Most common date format

1. Basic strftime Usage

from datetime import date, datetime
from zoneinfo import ZoneInfo

d = date(2026, 3, 19)
dt = datetime.now(ZoneInfo("UTC"))

print(d.strftime("%Y-%m-%d"))                    # 2026-03-19
print(d.strftime("%A, %B %d, %Y"))               # Thursday, March 19, 2026
print(dt.strftime("%Y-%m-%d %H:%M:%S"))          # 2026-03-19 14:30:25
print(dt.strftime("%A %d %B %Y at %I:%M %p"))    # Thursday 19 March 2026 at 02:30 PM

2. pandas – Vectorized strftime for Large Datasets

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_date"]   = df["order_date"].dt.strftime("%Y%m%d")        # 20260319
df["full_date"]   = df["order_date"].dt.strftime("%A, %B %d, %Y")

print(df[["order_date", "report_date", "full_date"]].head())

3. Real-World Data Science Examples

# Example 1: Generate daily report filenames
today_str = date.today().strftime("%Y%m%d")
filename = f"sales_report_{today_str}.csv"

# Example 2: Create human-readable log timestamps
log_time = datetime.now(ZoneInfo("UTC")).strftime("%Y-%m-%d %H:%M:%S UTC")

# 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() when you need machine-readable output
  • Apply pandas .dt.strftime() for large-scale formatting
  • Always format timezone-aware datetimes consistently
  • Define format constants at the top of your scripts for consistency

The Codes You Use Most

A small set of strftime codes covers most needs: %Y year, %m month, %d day, %H hour (24-hour), %I hour (12-hour) with %p for AM/PM, %M minute, %S second, %A and %a for weekday names, %B and %b for month names, and %z for the UTC offset.

The same codes work for parsing with strptime and pd.to_datetime(format=...), so learning them once serves both directions.

Some platform-specific extensions, such as removing zero padding, do not work everywhere, so stick to the standard codes in portable code.

Worked Example: One Timestamp, Many Formats

A single datetime is formatted with common codes and parsed back.

from datetime import datetime, timezone

dt = datetime(2026, 3, 19, 14, 5, 9, tzinfo=timezone.utc)
for fmt in ("%Y-%m-%d %H:%M:%S", "%d/%m/%Y", "%I:%M %p", "%a %d %b %Y", "%Y-%m-%dT%H:%M:%S%z"):
    print(f"{fmt:22} {dt.strftime(fmt)}")

parsed = datetime.strptime("19/03/2026 14:05", "%d/%m/%Y %H:%M")
print(parsed)

The loop prints the same moment in five styles, including 02:05 PM for the 12-hour format and +0000 for the offset. strptime uses the same codes to parse the day-first string back into a datetime.

Practical Tips

Keep a short reference of the codes your team uses in the project's README.

Common Mistakes

  • Mixing up %m and %M.
  • Using %H with %p instead of %I.
  • Relying on platform-specific codes.
  • Forgetting %z when the offset matters.

Quick Summary

  • Learn a small set of standard codes.
  • The same codes format and parse.
  • Use %I with %p for 12-hour clocks.
  • Include %z for offsets.

Conclusion

The strftime() method is the go-to tool for turning dates and times into any string format you need. In 2026 data science workflows, mastering common format codes and using pandas vectorized methods makes report generation, file naming, logging, and feature engineering fast, clean, and professional.

Next steps:

  • Add formatted date/time 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