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

Python Pandas - Lấy biểu diễn Timestamp của Period object

Để lấy biểu diễn Timestamp của đối tượng Period, sử dụng phương thức period.to_timestamp().

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

1. Import thư viện

import pandas as pd

2. Tạo Period object

period = pd.Period(freq="S", year=2021, month=9, day=18, hour=17, minute=20, second=45)

3. Chuyển sang Timestamp (mặc định giữ tần suất gốc)

print("\nPeriod thành Timestamp...\n", period.to_timestamp(freq='T'))

Ví dụ hoàn chỉnh

import pandas as pd

period = pd.Period(freq="S", year=2021, month=9, day=18, hour=17, minute=20, second=45)

print("Period...\n", period)
print("\nPeriod thành Timestamp (tần suất phút)...\n", period.to_timestamp(freq='T'))

Kết quả đầu ra

Period...
2021-09-18 17:20:45
Period thành Timestamp (tần suất phút)...
2021-09-18 17:20:00

Giải thích:

  • Period tần suất 'S' (giây) đại diện cho một giây cụ thể
  • Gọi to_timestamp() không đối số sẽ trả về Timestamp tại **đầu** khoảng thời gian đó
  • Với freq='S', đầu khoảng là chính giây đó → 17:20:45
  • Với freq='T', đầu khoảng là đầu phút → 17:20:00

Quy tắc chung

period.to_timestamp(freq=X) trả về Timestamp tại **đầu** (start) của khoảng thời gian khi biểu diễn ở tần suất X.

  • Period('2021-09', freq='M') → to_timestamp() → 2021-09-01 00:00:00 (đầu tháng)
  • Period('2021-Q3', freq='Q') → to_timestamp() → 2021-07-01 00:00:00 (đầu quý)
  • Period('2021', freq='Y') → to_timestamp() → 2021-01-01 00:00:00 (đầu năm)