Sponsored Reserved space — layout preview until AdSense is connected

Reference

Common datetime patterns in Python

Parsing, formatting, time zones, and durations — the datetime snippets you keep looking up.

May 2026 · 7 min read · 2 views · 0 hearts

Now, and timezone-aware now

from datetime import datetime, timezone, timedelta

naive = datetime.now()
aware = datetime.now(timezone.utc)

Format and parse

aware.strftime("%Y-%m-%d %H:%M")          # to string
datetime.strptime("2026-03-01", "%Y-%m-%d")  # from string

Durations with timedelta

deadline = aware + timedelta(days=7)
remaining = deadline - aware

Prefer timezone-aware datetimes for anything stored or compared across systems. Use the standard library's zoneinfo for named zones like Europe/Paris.

Comments

Questions, corrections, and tips stay visible for everyone reading this page.

0 in thread

Join the discussion

Shown next to your comment.

Constructive tone · up to 4,000 characters

No comments yet

Be the first to leave a note — it helps the next reader.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected