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

Python Pandas - สร้าง Timestamp ใหม่แทน UTC วันและเวลา

การสร้าง Timestamp ใหม่ที่แสดงเวลา UTC ปัจจุบัน

ใช้เมธอด timestamp.utcnow() คืนค่า Timestamp ใหม่ที่แสดงวันและเวลา UTC ปัจจุบัน

ขั้นตอน

  1. นำเข้า pandas
  2. สร้าง Timestamp ใด ๆ (พร้อม timezone UTC)
  3. ใช้ utcnow()

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

import pandas as pd

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

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

# สร้าง Timestamp ใหม่แทน UTC วันและเวลาปัจจุบัน
print("\nUTC day and time...\n", timestamp.utcnow())

ผลลัพธ์

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

หมายเหตุ

เมธอด utcnow() เป็น class method ไม่ขึ้นอยู่กับค่า Timestamp เดิม ใช้ได้โดยตรงจากคลาส: pd.Timestamp.utcnow()