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

Cách chuyển datetime sang timestamp UTC trong Python

Để lấy timestamp UTC chính xác từ đối tượng datetime, cần đảm bảo datetime là aware (có timezone UTC) trước khi gọi .timestamp().

Python 3.2+: Dùng timezone.utc

from datetime import datetime, timezone

dt = datetime(2015, 10, 19)  # Naive datetime
# Gán timezone UTC rõ ràng
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
print(timestamp)  # 1445212800.0

Python 2 (hoặc cách thủ công)

Trừ epoch UTC (1970-01-01) và lấy total_seconds().

from datetime import datetime

dt = datetime(2015, 10, 19)
epoch = datetime(1970, 1, 1)
timestamp = (dt - epoch).total_seconds()
print(timestamp)  # 1445212800.0

⚠️ Cạm bẫy thường gặp

# SAI: Naive datetime bị coi là local time
dt = datetime(2015, 10, 19)
print(dt.timestamp())  # Kết quả phụ thuộc múi giờ máy!

Tóm tắt

Phương phápPython versionĐộ tin cậy
dt.replace(tzinfo=timezone.utc).timestamp()3.2+✅ Cao nhất
(dt - datetime(1970,1,1)).total_seconds()2.7+, 3.x✅ Cao (nếu dt là UTC)
dt.timestamp() (naive)3.3+❌ Phụ thuộc máy

Luôn gán timezone UTC rõ ràng để tránh bug cross-platform.