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

Python Pandas - แปลง naive Timestamp เป็น local time zone

การเพิ่ม timezone ให้ naive Timestamp

ใช้เมธอด timestamp.tz_localize() เพื่อกำหนด timezone ให้กับ Timestamp ที่ไม่มี timezone (naive)

ขั้นตอน

  1. นำเข้า pandas
  2. สร้าง naive Timestamp (ไม่มี timezone)
  3. ใช้ tz_localize(tz='timezone') กำหนด timezone

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

import pandas as pd

# สร้าง naive Timestamp
timestamp = pd.Timestamp('2021-09-14T15:12:34.261811624')

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

# เพิ่ม timezone Australia/Brisbane
print("\nTimestamp to local time zone...\n", timestamp.tz_localize(tz='Australia/Brisbane'))

ผลลัพธ์

Timestamp... 2021-09-14 15:12:34.261811624
Timestamp to local time zone... 2021-09-14 15:12:34.261811624+10:00

คำอธิบาย

Timezone 'Australia/Brisbane' คือ UTC+10 เมธอด tz_localize จะเพิ่มข้อมูล timezone ให้กับ naive timestamp โดยไม่เปลี่ยนเวลาท้องถิ่น