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

So sánh time ở timezone khác nhau trong Python

Khi có 2 time object khác timezone cần so sánh, hiểu rõ aware (có tzinfo) vs naive (không tzinfo).

Cách dễ nhất so sánh 2 aware object: so sánh trực tiếp.

Ví dụ

import datetime, pytz

local_tz = pytz.timezone('CET')
utc = datetime.datetime.now(pytz.utc)
local = utc.astimezone(local_tz)

print("UTC:", utc)
print("Local:", local)
print(utc == local)  # True - cùng moment thời gian

Kết quả

UTC:  2024-01-15 10:30:45.123456+00:00
Local:  2024-01-15 11:30:45.123456+01:00
True

Lưu ý: So sánh naive với aware → TypeError. Luôn convert về cùng timezone (thường UTC) trước khi so sánh.