dmnte
dmnte

Reputation: 155

convert list of lists with time strings to seconds and find count times between

I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

Upvotes: 0

Views: 906

Answers (7)

Alexey
Alexey

Reputation: 409

from datetime import datetime, timedelta

arr = [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]

def convert(t):
    return datetime.strptime(t, "%H:%M:%S")

def append_start_end(element):
    if len(element) > 0:
        hour = element[0].split(":")[0]
        first = ["{}:00:00".format(hour)]
        last = ["{}:59:59".format(hour)]
        return first + element + last
    return []

result = []
for d in arr:
    d = append_start_end(d)
    result.append(
        [(convert(f[1]) - convert(f[0])  - timedelta(minutes=5) ).total_seconds()
         for f in zip(d[:-1], d[1:])
         if convert(f[1]) - convert(f[0])  > timedelta(minutes=5)]
    )

print(result)

Updated: removed steps in slices:

for f in zip(d[:-1:2], d[1::2])

Output now:

[[], [], [32.0, 2199.0], []]

Upvotes: 1

Thomas
Thomas

Reputation: 181745

The datetime module has most of what you need:

  • datetime is a class that represents a moment in time, like 1970-01-01 17:03:22 UTC.
  • datetime.strptime() can be used to create a datetime from a string.
  • The overloaded - operator on datetime objects gives you a timedelta, which has a total_seconds() method to convert it to seconds.

Note that the time class is closer to what you actually want to represent (a time of day, without the date part), but you cannot subtract two time objects.

Upvotes: 0

P.Madhukar
P.Madhukar

Reputation: 464

You can get difference count using this code. Just pass your list to this function.

import datetime
def countDifference(date_list):
    final_count = []
    for inner_dt in date_list:
        count = 0
        new_list = []

        for dt_elem in inner_dt:
            new_date = datetime.datetime.strptime(dt_elem, "%H:%M:%S")
            total_seconds = new_date.hour*60*60 + new_date.minute*60 + new_date.second
            new_list.append(total_seconds)
        new_list.sort()

        for first, second in zip(new_list, new_list[1:]):
            if second - first >= 300: count+=1
        final_count.append((inner_dt, count))

    return final_count

print countDifference([[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]])

Output:

[([], 0), ([], 0), (['17:03:22', '17:08:54', '17:50:33', '17:55:20'], 2), ([], 0)]

Upvotes: 0

petny
petny

Reputation: 21

Searching arbitrary nested lists can be done with a recursive function

def gap_count(lst):

    count = 0
    timetag_pair = []

    for elem in lst:

        if isinstance(elem, list):

            # Recursive use of gap_count when a nested list is encountered.
            count += gap_count(elem)

        elif isinstance(elem, str):

            timetag_pair.append(datetime.strptime(elem, '%H:%M:%S'))

        if len(timetag_pair) == 2:

            if abs((timetag_pair[0].minute + timetag_pair[0].second / 60.0) -
                   (timetag_pair[1].minute + timetag_pair[1].second / 60.0)) >= 5:

                count += 1

            timetag_pair = []

    return count

If you call gap_count with your test list it should return 1.

lst = [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]
gap_count(lst)
> 1

Upvotes: 0

bidi
bidi

Reputation: 66

I'd also use the datetime module, convert all the timestamps into a datetime object and use than the timedelta.

import datetime

inputarr = [[], [], ['17:03:22', '17:08:54', '17:50:33', '17:55:20'], []]

for currList in inputarr:
    dates = []
    for currTime in currList:
        dates.append(datetime.datetime.strptime(currTime, "%H:%M:%S"))
    elemDiff = [(j-i).seconds for i,j in zip(dates, dates[1:])]
    elemDiff.append(0) #added a 0 for same length of the lists
    for element in range(len(currList)):
        if elemDiff[element] > datetime.timedelta(minutes=5).seconds:
            print(currList[element])

Output:

17:03:22
17:08:54

Upvotes: 0

coder.in.me
coder.in.me

Reputation: 1068

This code will give the location, time and delay. You can easily count the number of occurences using len().

import datetime

event_times = [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]
threshold = 5*60

delayed = []
dt_prev_et = None
for i, ets in enumerate(event_times):
    for j, et in enumerate(ets):
        dt_et = datetime.datetime.strptime(et, "%H:%M:%S")
        if dt_prev_et is None:
            dt_prev_et = dt_et
            continue

        delay = (dt_et - dt_prev_et).seconds
        if delay > threshold:
            delayed.append((i, j, et, delay))

        dt_prev_et = dt_et

print(delayed)

Upvotes: 0

jimidime
jimidime

Reputation: 552

use datetime module to convert a string into time like below:

from datetime import datetime

first_time = "17:08:54"

second_time = "17:50:33"

format = "%H:%M:%S"

time_delta = datetime.strptime(second_time, FMT) -datetime.strptime(first_time, FMT)

count = 0
gap = 5
if time_delta.seconds >= 5*60:
    count+=1

Upvotes: 0

Related Questions