Để trích xuất số giây từ mỗi phần tử của TimeDeltaIndex, hãy sử dụng thuộc tính TimedeltaIndex.seconds.
Các bước thực hiện
1. Import thư viện
import pandas as pd
2. Tạo TimeDeltaIndex
tdIndex = pd.TimedeltaIndex(data=[
'10 day 5h 2 min 35s 3us 10ns',
'+22:39:19.999999',
'2 day 4h 03:08:02.000045',
'+21:15:45.999999'
])
3. Hiển thị TimedeltaIndex
print("TimedeltaIndex...\n", tdIndex)
4. Trích xuất giây
print("\nSố giây từ mỗi phần tử...\n", tdIndex.seconds)
Ví dụ hoàn chỉnh
import pandas as pd
tdIndex = pd.TimedeltaIndex(data=[
'10 day 5h 2 min 35s 3us 10ns',
'+22:39:19.999999',
'2 day 4h 03:08:02.000045',
'+21:15:45.999999'
])
print("TimedeltaIndex...\n", tdIndex)
print("\nSố giây từ mỗi phần tử...\n", tdIndex.seconds)
print("\nDataFrame các thành phần của TimeDeltas...\n", tdIndex.components)
Kết quả đầu ra
TimedeltaIndex...
TimedeltaIndex(['10 days 05:02:35.000003010', '0 days 22:39:19.999999',
'2 days 07:08:02.000045', '0 days 21:15:45.999999'],
dtype='timedelta64[ns]', freq=None)
Số giây từ TimeDeltaIndex...
Int64Index([18155, 81559, 25682, 76545], dtype='int64')
DataFrame các thành phần của TimeDeltas...
days hours minutes seconds milliseconds microseconds nanoseconds
0 10 5 2 35 0 3 10
1 0 22 39 19 999 999 0
2 2 7 8 2 0 45 0
3 0 21 15 45 999 999 0
Lưu ý: Thuộc tính seconds trả về số giây trong ngày (0-86399), không phải tổng số giây của timedelta. Ví dụ: '10 days 05:02:35' trả về 18155 giây (5h*3600 + 2*60 + 35), không phải 10*86400+18155. Để lấy tổng giây, dùng tdIndex.total_seconds().