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

Python Pandas - ดึงค่า UTC Offset Time

การดึงค่า UTC Offset จาก Timestamp

ใช้เมธอด timestamp.utcoffset() เพื่อดึงค่า offset จาก UTC ของ Timestamp ที่มี timezone

ขั้นตอน

  1. นำเข้า pandas
  2. สร้าง Timestamp พร้อม timezone UTC
  3. แสดง Timestamp
  4. ใช้ utcnow() ดูเวลา UTC ปัจจุบัน
  5. ใช้ utcoffset() ดึง offset

ตัวอย่างโค้ด

import pandas as pd

# สร้าง Timestamp พร้อม timezone UTC
timestamp = pd.Timestamp('2021-10-16T15:12:34.261811624', tz='UTC')

# แสดง Timestamp
print("Timestamp...\n", timestamp)

# แสดงเวลา UTC ปัจจุบัน
print("\nUTC day and time...\n", timestamp.utcnow())

# ดึง UTC offset
print("\nUTC offset time...\n", timestamp.utcoffset())

ผลลัพธ์

Timestamp... 2021-10-16 15:12:34.261811624+00:00
UTC day and time... 2021-10-03 07:56:44.685816+00:00
UTC offset time... 0:00:00

คำอธิบาย

เนื่องจาก Timestamp ถูกสร้างด้วย timezone UTC ดังนั้น offset คือ 0:00:00 หากใช้ timezone อื่น จะได้ offset ตามเขตเวลานั้น