-2

I have multiple times as a string:

"2018-12-14 11:20:16","2018-12-14 11:14:01","2018-12-14 11:01:58","2018-12-14 10:54:21"

I want to calculate the average time difference between all these times. The above example would be:

2018-12-14 11:20:16 - 2018-12-14 11:14:01 = 6 minutes 15 seconds
2018-12-14 11:14:01 - 2018-12-14 11:01:58 = 12 minutes 3 seconds
2018-12-14 11:14:01 - 2018-12-14 11:01:58 = 7 minutes 37 seconds

(375s+723s+457s)/3 = 518.3 seconds = 8 minutes 38.33 seconds (If my hand math is correct.)

I have all the datestrings in an array. I assume it's easy to convert it to a timestamp, loop over it to calculate the differences and then the average? I just began to learn python and this is the first program that I want to do for myself.

whitefleaCH
  • 67
  • 1
  • 9
  • 2
    Possible duplicate of [How to calculate the time interval between two time strings](https://stackoverflow.com/questions/3096953/how-to-calculate-the-time-interval-between-two-time-strings) – kabanus Dec 14 '18 at 13:46
  • If you want it to do yourself..I assume you should try out something..post code of what you tried..where are you getting errors and so on – Rahul Agarwal Dec 14 '18 at 13:47
  • The dup target will get you the intervals, I am assuming you can then do the average. – kabanus Dec 14 '18 at 13:47
  • also, have a look at [itertools.combinations](https://docs.python.org/3/library/itertools.html#itertools.combinations) – Pynchia Dec 14 '18 at 13:54

2 Answers2

4

You have a bunch of problems. I'm not going to give you solutions to all of these. Just hints to get you started.

I assume you know...

  • ... how to convert a time string to a datetime.datetime object,
  • ... how to calculate the difference between two, i.e., a datetime.timedelta,
  • ... how to compute a mean value (datetime.timedelta supports both addition and division by int or float).

So the only complicated step in this task will be, how to calculate the differences between adjacent items in a list. I'm going to show you this.

When you have a list of items, you can slice and zip to produce an iterator to iterate the pairs of adjacent elements in the list.

For example, try this (untested code):

l = range(10)
for i,j in zip(l, l[1:]):
    print(i, j)

Then build a list to contain the differences, e.g., using a list comprehension:

deltas = [i-j for i,j in zip(l, l[1:])]

Now calculate your mean value and you're done.

For reference:

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
1
from datetime import datetime
import numpy as np

ts_list = ["2018-12-14 11:20:16","2018-12-14 11:14:01","2018-12-14 11:01:58","2018-12-14 10:54:21"]
dif_list = []
for i in range(len(ts_list)-1):
    dif_list.append((datetime.strptime(ts_list[i], '%Y-%m-%d %H:%M:%S')-datetime.strptime(ts_list[i+1], '%Y-%m-%d %H:%M:%S' )).total_seconds())
avg = np.mean(dif_list)
print(avg)

result is 518.3333333333334 seconds.

Neo
  • 627
  • 3
  • 7