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

Python Pandas - จัดรูปแบบและคืนค่าสตริงของ Period Object

เพื่อจัดรูปแบบและคืนค่าสตริงของ Period object ให้ใช้เมธอด period.strftime() พร้อม format specifiers เช่น strftime('%d-%b-%Y')

ขั้นตอนการทำงาน

1. นำเข้าไลบรารีที่จำเป็น

import pandas as pd

2. สร้าง Period Object

period = pd.Period(freq="S", year=2021, month=9, day=18, hour=8, minute=20, second=45)

3. แสดง Period Object

print("Period...\n", period)

4. แสดงสตริงที่จัดรูปแบบแล้ว

print("\nString representation (format)...\n", period.strftime('%d-%b-%Y'))
print("\nString representation (format with different directives)...\n", period.strftime('%b. %d, %Y was a %A'))

ตัวอย่างโค้ดสมบูรณ์

import pandas as pd

# สร้าง Period object
period = pd.Period(freq="S", year=2021, month=9, day=18, hour=8, minute=20, second=45)

# แสดง Period object
print("Period...\n", period)

# แสดงรูปแบบวันที่สั้น
print("\nString representation (format)...\n", period.strftime('%d-%b-%Y'))

# แสดงรูปแบบวันที่ยาว
print("\nString representation (format with different directives)...\n", period.strftime('%b. %d, %Y was a %A'))

ผลลัพธ์ที่คาดหวัง

Period... 
2021-09-18 08:20:45
String representation (format)... 
18-Sep-2021
String representation (format with different directives)... 
Sep. 18, 2021 was a Saturday

Format Specifiers ที่ใช้บ่อย:

  • %d - วัน (01-31)
  • %b - ชื่อเดือนย่อ (Jan-Dec)
  • %Y - ปี 4 หลัก
  • %A - ชื่อวันเต็ม (Monday-Sunday)