chowpay
chowpay

Reputation: 1687

creating a sequential pair of time lists

I have a list of times that look like this, every time is incremented by 5 mins with the last time being 23:59:00.000

list_of_times = ['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000', '2020-01-30 00:10:00.000', '2020-01-30 00:15:00.000', '2020-01-30 00:20:00.000'... '2020-01-30 23:59:00.000']

What I want to do is end up with a list of time pairs like this:

list_of_pairs = [['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000'],['2020-01-30 00:05:00.000','2020-01-30 00:05:00.000'], ... ['2020-01-30 23:55:00.000','2020-01-30 23:59:00.000']]

So note how in the list_of_pairs the end time of the first pair ['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000'], is the start time for the next pair ['2020-01-30 00:05:00.000','2020-01-30 00:05:00.000']

My code:

start_times = list_of_times[::2]
end_times = list_of_times[1::2]
count = 0
try:
    for item in start_times:
        pair_of_times.append([start_times[count],end_times[count]])
        count +=1
except:
    pass
print(pair_of_times)

But my result is as expected, note how the start time of the 2nd pair is 2020-01-30 00:10:00.000'. I would like it to be the end time of the previous pair. Here is how my result looks now :

[['2020-01-30 00:00:00.000', '2020-01-30 00:05:00.000'], ['2020-01-30 00:10:00.000', '2020-01-30 00:15:00.000']...]

Not sure how to slice correctly, or even if slicing is the right method to get the result I'm looking for. I'm also open to generating the time from scratch since I'm given the start and end time ie start = '2020-01-30 00:00:00.000'. end = '2020-01-30 23:59:00.000'

Upvotes: 2

Views: 36

Answers (1)

user2390182
user2390182

Reputation: 73450

You could remedy this by using step=1 on your slices, since every time (except the first and last) will be both a start and an end time, so you should not skip any time in either list:

# ...
start_times = list_of_times  # no slice needed at all
end_times = list_of_times[1:]
# ...

You can further simplify this by using a typical pattern using zip:

pair_of_times = list(zip(list_of_times, list_of_times[1:]))

More space efficient yet:

pair_of_times = [list_of_times[i:i+2] for i in range(len(list_of_times) - 1)]

Upvotes: 1

Related Questions