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

Python Pandas - Lấy tổng số ngày của tháng chứa Period

Để lấy tổng số ngày của tháng mà đối tượng Period rơi vào, sử dụng thuộc tính period.daysinmonth.

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") (tháng 9 có 30 ngày)
    • period2 = pd.Period(freq="D", year=2021, month=2, day=14, hour=2, minute=35) (tháng 2 năm 2021 có 28 ngày)
  3. Truy cập period1.daysinmonth và period2.daysinmonth.

Ví dụ hoàn chỉnh

import pandas as pd

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

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

res1 = period1.daysinmonth
res2 = period2.daysinmonth

print("\nReturn Days in the month from the 1st Period object ...\n", res1)  # 30
print("\nReturn Days in the month from the 2nd Period object ...\n", res2)   # 28

Kết quả

Period1... 2020-09-23
Period2... 2021-02-14
Return Days in the month from the 1st Period object ... 30
Return Days in the month from the 2nd Period object ... 28