Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Lấy năm từ Period object

Để 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ĩaVí dụ
yearNăm2021
monthTháng (1-12)9
dayNgày (1-31)18
hourGiờ (0-23)17
minutePhút (0-59)20
secondGiây (0-59)45
weekdayThứ trong tuần (0=Thứ 2)5 (Thứ 7)
weekofyear / weekTuần trong năm39
quarter / qQuý (1-4)3
days_in_monthSố ngày trong tháng30