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

Python Pandas - แปลง Timestamp เป็น Period ด้วยความถี่รายไตรมาส

การแปลง Timestamp เป็น Period (ความถี่รายไตรมาส)

ใช้เมธอด timestamp.to_period(freq='Q') แปลง Timestamp เป็น Period แบบรายไตรมาส

ขั้นตอน

  1. นำเข้า pandas
  2. สร้าง Timestamp
  3. ใช้ to_period(freq='Q')

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

import pandas as pd

# สร้าง Timestamp
timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)

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

# แปลงเป็น Period ความถี่รายไตรมาส
print("\nTimestamp to Period with quarterly frequency...\n", timestamp.to_period(freq='Q'))

ผลลัพธ์

Timestamp... 2021-09-18 11:50:20.000033
Timestamp to Period with quarterly frequency... 2021Q3

คำอธิบาย

ไตรมาสที่ 3 (Q3) ครอบคลุมเดือน กรกฎาคม-สิงหาคม-กันยายน วันที่ 18 กันยายน จึงอยู่ใน Q3