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

Python Pandas - จัดรูปแบบ Period และแสดงปีไม่รวมศตวรรษ

เพื่อจัดรูปแบบ Period object ให้ใช้เมธอด period.strftime() เพื่อแสดงปีไม่รวมศตวรรษ ใช้ format specifier %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. แสดงปีไม่รวมศตวรรษ

%y แสดงปี 2 หลักสุดท้าย (ไม่รวมศตวรรษ)

print("\nString representation (year without century)...\n", period.strftime('%y'))

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

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 (year without century)...\n", period.strftime('%y'))

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

Period... 
2021-09-18 08:20:45
String representation (year without century)... 
21

คำอธิบาย: strftime('%y') คืนค่าปี 2 หลักสุดท้าย สำหรับปี 2021 จะได้ 21