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

Lấy local timezone trong Python

Computer's UTC offset = timezone set trên máy. Lấy bằng module time: time.timezone trả về UTC offset tính bằng giây (âm vì West of UTC).

Ví dụ

import time
print(-time.timezone)  # India: +5:30 = 19800 seconds

Kết quả

19800

Cách khác: So sánh local vs UTC datetime

import time
from datetime import datetime

ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) - datetime.utcfromtimestamp(ts)).total_seconds()
print(utc_offset)  # 19800

Lưu ý: time.timezone không tính DST. Dùng time.altzone cho DST offset. Khuyến nghị dùng tzlocal.get_localzone() hoặc zoneinfo (Python 3.9+) để lấy timezone object đầy đủ.