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

Python Pandas - Tìm thời gian bắt đầu của Period object

Để tìm thời gian bắt đầu (start time) của Period object, sử dụng thuộc tính period.start_time.

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-22")
period2 = pd.Period(freq="D", year=2021, month=2, day=14, hour=2, minute=35)

3. Lấy thời gian bắt đầu

res1 = period1.start_time
res2 = period2.start_time

Ví dụ hoàn chỉnh

import pandas as pd

period1 = pd.Period("2020-09-22")
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.start_time
res2 = period2.start_time

print("\nThời gian bắt đầu từ Period1...\n", res1)
print("\nThời gian bắt đầu từ Period2...\n", res2)

Kết quả đầu ra

Period1...
2020-09-22
Period2...
2021-02-14
Thời gian bắt đầu từ Period1...
2020-09-22 00:00:00
Thời gian bắt đầu từ Period2...
2021-02-14 00:00:00

Giải thích:

  • start_time trả về Timestamp tại **đầu** của khoảng thời gian Period
  • Period1 (tần suất ngày) → 2020-09-22 00:00:00
  • Period2 (tần suất ngày, nhưng tạo với hour=2) → vẫn trả về 00:00:00 vì tần suất là ngày

Các thuộc tính liên quan:

Thuộc tínhTrả vềÝ nghĩa
start_timeTimestampĐầu khoảng thời gian
end_timeTimestampCuối khoảng thời gian
to_timestamp()TimestampĐầu khoảng (mặc định), có thể đổi freq
period = pd.Period('2021-09', freq='M')
period.start_time  # 2021-09-01 00:00:00
period.end_time    # 2021-09-30 23:59:59.999999999