Skip to main content

Working with `datetime`

Standard Library

Mastering datetime

Handle timestamps like a pro: parsing ISO strings, building time zone–aware objects, and doing arithmetic safely.

Cheatsheet

Common datetime recipes
TaskCode
Current UTC timedatetime.datetime.utcnow()
Current local timedatetime.datetime.now()
Parse ISO stringdatetime.datetime.fromisoformat('2024-03-13T09:00:00')
Format stringts.strftime('%Y-%m-%d %H:%M')
Add 7 daysts + datetime.timedelta(days=7)

Time zones

  • Use the zoneinfo module (Python 3.9+) for IANA timezone data.
from datetime import datetime
from zoneinfo import ZoneInfo

now = datetime.now(ZoneInfo('UTC'))
local = now.astimezone(ZoneInfo('America/New_York'))
  • Always store timestamps in UTC internally; convert at boundaries.

Best practices

  • Use datetime.date for date-only values and datetime.time for time-only.
  • Serialize to ISO 8601 strings for APIs (dt.isoformat()).
  • Beware naive vs aware datetimes—mixing them raises TypeError.

Next up in your learning path