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

Python Pandas - Lấy ngày trong tháng (day of month) từ đối tượng Period

Để lấy ngày trong tháng (day of month) mà đối tượng Period rơi vào, sử dụng thuộc tính period.day.

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("2021-09-18")
    • period2 = pd.Period(freq='D', year=2021, month=9, day=22, hour=4, minute=55)
  3. Truy cập period1.day và period2.day.

Ví dụ hoàn chỉnh

import pandas as pd

period1 = pd.Period("2021-09-18")
period2 = pd.Period(freq='D', year=2021, month=9, day=22, hour=4, minute=55)

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

res1 = period1.day
res2 = period2.day

print("\nDay of the month from the 1st Period object ...\n", res1)  # 18
print("\nDay of the month from the 2nd Period object...\n", res2)   # 22

Kết quả

Period1... 2021-09-18
Period2... 2021-09-22
Day of the month from the 1st Period object ... 18
Day of the month from the 2nd Period object... 22