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-09-14T15:12:34.261811624')

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

# แปลงเป็น Period ความถี่รายเดือน
print("\nTimestamp to Period...\n", timestamp.to_period(freq='M'))

ผลลัพธ์

Timestamp... 2021-09-14 15:12:34.261811624
Timestamp to Period... 2021-09

สรุปความถี่ที่ใช้บ่อย

  • 'D' = รายวัน (Daily)
  • 'W' = รายสัปดาห์ (Weekly)
  • 'M' = รายเดือน (Month end)
  • 'Q' = รายไตรมาส (Quarterly)
  • 'H' = รายชั่วโมง (Hourly)
  • 'T' = รายนาที (Minutely)
  • 'S' = รายวินาที (Secondly)