Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีหา Local Timezone ใน Python

Computer's UTC Offset คือ Timezone ที่ตั้งบนเครื่อง ใช้ Module time ได้ time.timezone คืน UTC Offset ในวินาที

ตัวอย่าง

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

ผลลัพธ์

19800

วิธีอื่น: สร้าง Datetime Objects สำหรับ UTC และ Local ลบกันหา Difference

import time
from datetime import datetime

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

ผลลัพธ์

19800