列表中两个元素之间每个元素的时间增量

Time delta for each element between two elements in a list

我正在尝试获取列表中每两个日期时间元素之间的增量时间。但每次我尝试某事时,都会出现索引错误或值不正确。 在列表之外,我在某些情况下面临负值。鉴于没有负时间,这是不可能的。

例如:time_delta_list = [-2, 0, 8, 6]

我应该如何在 for 循环中执行此操作?

代码:

assignment_date = [['US01', datetime.datetime(2020, 10, 20, 6, 59)], ['US03', datetime.datetime(2020, 10, 28, 9, 8)], ['US02', datetime.datetime(2020, 10, 29, 8, 54)], ['US05', datetime.datetime(2020, 10, 29, 15, 5)], ['US09', datetime.datetime(2020, 11, 2, 7, 57)], ['US10', datetime.datetime(2020, 11, 2, 7, 57)], ['US11', datetime.datetime(2020, 11, 2, 7, 58)], ['US04', datetime.datetime(2020, 11, 2, 7, 59)]]
time_delta_list = []
 

for index, elem in enumerate(assignment_date):     
        
            if index == 0:
                time_delta = elem[1] - datetime(day=7, month=9, year=2020, hour=10, minute=30)
                time_delta_list.append(time_delta)
                
            if index + 1 < len(assignment_date):
                current_date = elem[1]
                next_date = assignment_date[index+1][1]
                
                time_delta = next_date - current_date
                time_delta_list.append(time_delta)


-----------------------------------------------------------------------------
              
Traceback (most recent call last):
  File "delta_time_assignments.py", line 147, in <module>
    next_date = fed_lists[index+1][1]
IndexError: list index out of range

使用 pandas 相当容易,不需要弄乱索引

import datetime
import pandas

assignment_date = [['US01', datetime.datetime(2020, 10, 20, 6, 59)], ['US03', datetime.datetime(2020, 10, 28, 9, 8)], ['US02', datetime.datetime(2020, 10, 29, 8, 54)], ['US05', datetime.datetime(2020, 10, 29, 15, 5)], ['US09', datetime.datetime(2020, 11, 2, 7, 57)], ['US10', datetime.datetime(2020, 11, 2, 7, 57)], ['US11', datetime.datetime(2020, 11, 2, 7, 58)], ['US04', datetime.datetime(2020, 11, 2, 7, 59)]]

df = pandas.DataFrame(assignment_date)
df = df.rename(columns={0:'key', 1:'initial_date'})
initial_date = datetime.datetime(day=7, month=9, year=2020, hour=10, minute=30)

df['shift'] = df['initial_date'].shift(1, fill_value=initial_date)
df['delta'] = df['initial_date'] - df['shift']

print(df)