Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

In Python datetime theo local timezone

Cách dễ nhất xử lý timezone: pytz và tzlocal. Cho phép tính toán timezone chính xác, cross-platform.

Cài đặt

$ pip install pytz tzlocal

Ví dụ

from datetime import datetime
from pytz import timezone
from tzlocal import get_localzone

fmt = "%Y-%m-%d %H:%M:%S %Z%z"

# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(fmt))

# Convert to local timezone
now_local = now_utc.astimezone(get_localzone())
print(now_local.strftime(fmt))

Kết quả

2024-01-15 10:30:45 UTC+0000
2024-01-15 17:30:45 ICT+0700

Python 3.9+: Dùng zoneinfo built-in thay pytz.