I
I
Ilya2021-12-20 17:57:05
Python
Ilya, 2021-12-20 17:57:05

Calculate the average delay in time?

Good afternoon,
I have a list of datetime :

[datetime.datetime(2021, 12, 20, 16, 54, 56), datetime.datetime(2021, 12, 20, 16, 54, 57), datetime.datetime(2021, 12, 20, 16, 54, 57)]


I want to somehow get the average delay between dates (in seconds).

It would be possible to remove the middle element, and count them already, but this is not accurate.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Drill, 2021-12-20
@stead

dates = [datetime.datetime(2021, 12, 20, 16, 54, 56), datetime.datetime(2021, 12, 20, 16, 54, 57), datetime.datetime(2021, 12, 20, 16, 54, 57)]

average = sum(abs(x-y).total_seconds() for x, y in zip(dates, dates[1:])) / (len(dates) - 1)
print(average)

>>> 0.5

S
ScriptKiddo, 2021-12-20
@ScriptKiddo

from more_itertools import windowed
import datetime
import statistics

dates = [
    datetime.datetime(year=2021, month=12, day=20, hour=16, minute=54, second=56),
    datetime.datetime(year=2021, month=12, day=20, hour=16, minute=54, second=57),
    datetime.datetime(year=2021, month=12, day=20, hour=16, minute=54, second=57),
]


diffs = []

for first, second in windowed(dates, 2):
    diffs.append((second-first).total_seconds())

print(f'Avg: {statistics.mean(diffs)}')

Avg: 0.5

Process finished with exit code 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question