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

Python Pandas - Lấy ngày trong năm (day of year) từ đối tượng Period

Để lấy ngày trong năm (day of year) từ đối tượng Period, sử dụng thuộc tính period.dayofyear. Giá trị trả về từ 1-365 (năm thường) hoặc 1-366 (năm nhuận).

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") (2020 là năm nhuận)
    • period2 = pd.Period(freq="D", year=2021, month=7, day=16, hour=2, minute=35)
  3. Truy cập period1.dayofyear và period2.dayofyear.

Ví dụ hoàn chỉnh

import pandas as pd

period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year=2021, month=7, day=16, hour=2, minute=35)

print("Period1...\n", period1)
print("Period2...\n", period2)

res1 = period1.dayofyear
res2 = period2.dayofyear

print("\nDay of the year from the 1st Period object ...\n", res1)  # 267
print("\nDay of the year from the 2nd Period object...\n", res2)   # 197

Kết quả

Period1... 2020-09-23
Period2... 2021-07-16
Day of the year from the 1st Period object ... 267
Day of the year from the 2nd Period object... 197