python 中的下一个时间值减去上一个时间值

subtraction of previous time value from the next time value in python

我得到了这个时间数组,我需要从下一个值中减去上一个值。就像第 1 行到第 2 行和第 3 行到第 4 行。我已经为此苦苦挣扎了好几天,现在的问题是我将如何进行减法。

这是数据:

2017-12-21T14:49:17.518Z
2017-12-21T14:50:49.723Z
2017-12-21T14:50:54.028Z
2017-12-21T14:50:54.343Z
2017-12-21T14:50:59.084Z
2017-12-21T14:50:59.399Z
2017-12-21T14:51:04.142Z
2017-12-21T14:51:04.457Z
2017-12-21T14:51:09.204Z
2017-12-21T14:51:09.521Z
2017-12-21T14:51:14.261Z
2017-12-21T14:51:14.579Z
2017-12-21T14:51:19.326Z
2017-12-21T14:51:19.635Z
2017-12-21T14:51:24.376Z
2017-12-21T14:51:24.691Z
2017-12-21T14:51:29.435Z
2017-12-21T14:51:29.750Z
2017-12-21T14:51:34.498Z
2017-12-21T14:51:34.813Z

我需要用第一个减去第二个,用第四个减去第三个,用第六个减去第五个,等等。然后将结果放在另一个数组中并将它们相加。

这是通过 dateutil.parser.parse 的一种方式:

from dateutil import parser

lst = ['2017-12-21T14:49:17.518Z',
       '2017-12-21T14:50:49.723Z',
       '2017-12-21T14:50:54.028Z',
       '2017-12-21T14:50:54.343Z',
       '2017-12-21T14:50:59.084Z',
       '2017-12-21T14:50:59.399Z']

lst = list(map(parser.parse, lst))
changes = [(j-i) for i, j in zip(lst, lst[1:])][::2]

要将其转换为秒:

seconds = [i.total_seconds() for i in changes]

下面是使用 datetime 库和 strptime 函数的方法:

从你的previous question来看,你的时间似乎是一个字符串列表。

times = [
    '2017-12-21T14:49:17.518Z',
    '2017-12-21T14:50:49.723Z',
    '2017-12-21T14:50:54.028Z',
    '2017-12-21T14:50:54.343Z',
    '2017-12-21T14:50:59.084Z',
    '2017-12-21T14:50:59.399Z',
    '2017-12-21T14:51:04.142Z',
    '2017-12-21T14:51:04.457Z',
    '2017-12-21T14:51:09.204Z',
    '2017-12-21T14:51:09.521Z',
    '2017-12-21T14:51:14.261Z',
    '2017-12-21T14:51:14.579Z',
    '2017-12-21T14:51:19.326Z',
    '2017-12-21T14:51:19.635Z',
    '2017-12-21T14:51:24.376Z',
    '2017-12-21T14:51:24.691Z',
    '2017-12-21T14:51:29.435Z',
    '2017-12-21T14:51:29.750Z',
    '2017-12-21T14:51:34.498Z',
    '2017-12-21T14:51:34.813Z'
]

使用 strptime 将它们转换为日期时间对象。map() 函数将一个函数应用于可迭代对象中的每个元素。

times_converted = map(
    lambda x: datetime.datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%fZ'), 
    times
)

上面 strptime 的第二个参数是 format string,它定义了转换应该如何发生。

现在可以连续相减,用datetime.timedeltatotal_seconds()方法求差:

diffs = [
    (b-a).total_seconds() for a, b in zip(times_converted[::2], times_converted[1::2])
]
#[92.205, 0.315, 0.315, 0.315, 0.317, 0.318, 0.309, 0.315, 0.315, 0.315]

我用了zip() to get pairs of times from the list to subtract. The notation [::2] means take every other item in the list, starting at index 0. Likewise [1::2] means take every other item in the list, starting at index 1. More on python's slice notation here.

如果您对列表理解和 zip() 不满意,上面的代码也可以写成单个 for 循环:

diffs = []
for i in range(0,len(times), 2):
    diffs.append((times_converted[i+1]-times_converted[i]).total_seconds())

更多关于zip()

zip() 函数采用两个可迭代对象和 returns 对元组。例如,请考虑以下示例:

# suppose you had two lists
X = ['A', 'B', 'C']
Y = ['X', 'Y', 'Z']
print(zip(X, Y))
#[('A', 'X'), ('B', 'Y'), ('C', 'Z')]

所以本质上它从第一个列表中获取一个项目,从第二个列表中获取一个项目,并且 returns 这是一个元组。