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

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

การแปลง Timestamp เป็น Period (ความถี่รายเดือน)

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

ขั้นตอน

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

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

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 monthly frequency...\n", timestamp.to_period(freq='M'))

ผลลัพธ์

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

คำอธิบาย

ความถี่ 'M' (Month end) จะคืนค่า Period ที่แสดงปีและเดือนเท่านั้น (วันที่และเวลาถูกตัดทิ้ง)