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

Python Pandas - Lấy thành phần giây (second) của đối tượng Period

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

Các bước thực hiện

  1. Import thư viện: import pandas as pd
  2. Tạo đối tượng Period:
    • period1 = pd.Period("2020-09-23 05:55:30") (từ chuỗi)
    • period2 = pd.Period(freq="S", year=2021, month=7, day=16, hour=2, minute=35, second=10) (từ các thành phần, tần suất giây)
  3. Truy cập period1.second và period2.second.

Ví dụ hoàn chỉnh

import pandas as pd

# Tạo hai Period object
period1 = pd.Period("2020-09-23 05:55:30")
period2 = pd.Period(freq="S", year=2021, month=7, day=16, hour=2, minute=35, second=10)

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

# Lấy thành phần giây
res1 = period1.second
res2 = period2.second

print("\nSeconds component from the 1st Period object ...\n", res1)
print("\nSeconds component from the 2nd Period object ...\n", res2)

Kết quả

Period1... 2020-09-23 05:55:30
Period2... 2021-07-16 02:35:10
Seconds component from the 1st Period object ... 30
Seconds component from the 2nd Period object ... 10

Lưu ý: Period đại diện cho một khoảng thời gian (ví dụ: một giây, một phút, một ngày) thay vì một thời điểm cụ thể như Timestamp.