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

Python Pandas - Lấy giờ (hour) trong ngày từ đối tượng Period

Để lấy thành phần giờ (hour) trong ngày của đối tượng Period, sử dụng thuộc tính period.hour.

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 05:55:30")
    • period2 = pd.Period(freq="H", year=2021, month=7, day=16, hour=2, minute=35) (tần suất giờ)
  3. Truy cập period1.hour và period2.hour.

Ví dụ hoàn chỉnh

import pandas as pd

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

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

res1 = period1.hour
res2 = period2.hour

print("\nHour of the day from the 1st Period object ...\n", res1)  # 5
print("\nHour of the day from the 2nd Period object...\n", res2)   # 2

Kết quả

Period1... 2020-09-23 05:55:30
Period2... 2021-07-16 02:00
Hour of the day from the 1st Period object ... 5
Hour of the day from the 2nd Period object... 2