Python Datetime
Timezone-aware dates without the classic naive pitfalls.
- python datetime
- timezone aware
- isoformat
- strptime
- zoneinfo
Python Datetime
Timezone-aware dates without the classic naive pitfalls.
Commands
| Command | What it does |
|---|---|
datetime.now(timezone.utc) | Aware 'now' in UTC |
dt.astimezone(ZoneInfo("Asia/Shanghai")) | Convert zones |
dt.isoformat() | Serialize to ISO 8601 |
datetime.fromisoformat(s) | Parse ISO back |
(b - a).total_seconds() | Duration in seconds |
Example
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
now = datetime.now(timezone.utc)
print(now.astimezone(ZoneInfo("Asia/Shanghai")).isoformat())
FAQ
Naive vs aware datetimes?
Naive has no zone and breaks across DST; always store UTC-aware and convert only for display.
How to parse arbitrary formats?
datetime.strptime for fixed formats; dateutil.parser.isoparse for lenient ISO input.
Частые вопросы
Naive vs aware datetimes?
Naive has no zone and breaks across DST; always store UTC-aware and convert only for display.
How to parse arbitrary formats?
datetime.strptime for fixed formats; dateutil.parser.isoparse for lenient ISO input.
Python
Python Venv and Environments
Isolate dependencies per project with venv and pinned requirements.
Python Pip Essentials
Install, upgrade, and audit packages with pip like a pro.
Python Basics
Syntax survival kit: variables, loops, f-strings, and errors.
Python Strings
Slice, split, join, and format text efficiently.