Intermediate·18 min·0/47 done

Python Dates

Create datetimes, add durations, format and parse timestamps, and prefer UTC.

Why it matters: Log timestamps, training windows, and daily token reports all use datetime.

Basics

datetime Objects

The datetime module gives you date, datetime, timedelta, and timezone.

Prefer UTC for stored data: datetime.now(timezone.utc).

A datetime is naive (no timezone) or aware (has one). Mixing them raises TypeError.

Tiny example

Create an aware UTC datetime and print ISO format.

from datetime import datetime, timezone
now = datetime(2026, 9, 4, tzinfo=timezone.utc)
print(now.isoformat())

Basics

Format and Parse

strftime formats a datetime as text. strptime parses text into a datetime.

For machine data use ISO: dt.isoformat() and datetime.fromisoformat().

Common codes: %Y year, %m month, %d day, %H hour, %M minute, %S second.

Tiny example

Parse a log timestamp with strptime.

from datetime import datetime
print(datetime.strptime("2026-09-04 10:22:31", "%Y-%m-%d %H:%M:%S"))

Basics

timedelta and Timing

timedelta is a duration. Subtract two datetimes to get one.

Store UTC, display local. Use aware datetimes at API and database boundaries.

Measure work time with time.perf_counter(), not datetime.now() differences.

Tiny example

Measure a short loop with perf_counter.

import time
start = time.perf_counter()
_ = sum(range(1000))
print(round((time.perf_counter() - start) * 1000, 3), "ms")

Then AI / ML

AI / ML examples

Same idea, used in real AI work. Press Try in lab to run it.

AI / ML example

AI / ML: training window duration

Subtract two aware datetimes to get hours.

In AI / ML: Run manifests store started/finished UTC stamps and derive duration.

example.py

Python

from datetime import datetime, timedelta, timezone

start = datetime(2026, 9, 1, 9, 0, tzinfo=timezone.utc)
end = datetime(2026, 9, 4, 17, 30, tzinfo=timezone.utc)
duration = end - start
print(round(duration.total_seconds() / 3600, 2), "hours")
print("next run:", (end + timedelta(hours=6)).isoformat())

AI / ML example 2

AI / ML: group tokens by day

Key each call on its UTC date.

In AI / ML: Token-usage rollups key on the UTC date of each LLM call.

example.py

Python

from collections import defaultdict
from datetime import datetime, timezone

calls = [
    {"ts": "2026-09-02T10:00:00+00:00", "tokens": 500},
    {"ts": "2026-09-02T18:30:00+00:00", "tokens": 700},
    {"ts": "2026-09-03T09:15:00+00:00", "tokens": 1200},
]
by_day = defaultdict(int)
for call in calls:
    day = datetime.fromisoformat(call["ts"]).astimezone(timezone.utc).date()
    by_day[day] += call["tokens"]
print(dict(by_day))

Takeaways

  • 1Store UTC with aware datetimes; convert to local only for display.
  • 2Use isoformat/fromisoformat for machine data.
  • 3Measure elapsed time with time.perf_counter.
Certificate