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

Python Pandas - Trích xuất giây từ DateTimeIndex


Để lấy phần giây (0-59) từ DateTimeIndex, sử dụng thuộc tính DateTimeIndex.second.

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

1. Import thư viện

import pandas as pd

2. Tạo DateTimeIndex tần suất giây

datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='S')

3. Hiển thị DateTimeIndex

print("DateTimeIndex...\n", datetimeindex)

4. Lấy giây

print("\nPhần giây...\n", datetimeindex.second)

Ví dụ hoàn chỉnh

import pandas as pd

datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='S')

print("DateTimeIndex...\n", datetimeindex)
print("Tần suất...\n", datetimeindex.freq)
print("\nPhần giây...\n", datetimeindex.second)

Kết quả đầu ra

DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+11:00', '2021-10-20 02:30:51+11:00',
               '2021-10-20 02:30:52+11:00', '2021-10-20 02:30:53+11:00',
               '2021-10-20 02:30:54+11:00', '2021-10-20 02:30:55+11:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='S')
Tần suất...
<Second>
Phần giây...
Int64Index([50, 51, 52, 53, 54, 55], dtype='int64')

Lưu ý: Tần suất 'S' tạo các timestamp cách nhau 1 giây. Giá trị giây tăng dần từ 50 đến 55.