Để lấy năm từ Period object, sử dụng thuộc tính period.year.
Các bước thực hiện
1. Import thư viện
import pandas as pd
2. Tạo hai Period object
period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year=2021, month=4, day=16, hour=2, minute=35)
3. Lấy năm
res1 = period1.year
res2 = period2.year
Ví dụ hoàn chỉnh
import pandas as pd
period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year=2021, month=4, day=16, hour=2, minute=35)
print("Period1...\n", period1)
print("Period2...\n", period2)
res1 = period1.year
res2 = period2.year
print("\nNăm từ Period1...\n", res1)
print("\nNăm từ Period2...\n", res2)
Kết quả đầu ra
Period1...
2020-09-23
Period2...
2021-04-16
Năm từ Period1...
2020
Năm từ Period2...
2021
Các thuộc tính truy xuất thành phần thời gian của Period:
| Thuộc tính | Ý nghĩa | Ví dụ |
|---|---|---|
| year | Năm | 2021 |
| month | Tháng (1-12) | 9 |
| day | Ngày (1-31) | 18 |
| hour | Giờ (0-23) | 17 |
| minute | Phút (0-59) | 20 |
| second | Giây (0-59) | 45 |
| weekday | Thứ trong tuần (0=Thứ 2) | 5 (Thứ 7) |
| weekofyear / week | Tuần trong năm | 39 |
| quarter / q | Quý (1-4) | 3 |
| days_in_month | Số ngày trong tháng | 30 |