Getting the Initial and the end of consecutive dates Numpy Python

Viewed 62

I want to write a code where it compares dates and selected_dates and states the intervals selected_dates occupies within dates and does not occupy. So it looks for consecutive number of times dates are in both dates and selected_dates have been in each other and records the timestamp of the start and end. The inverse as well so the consecutive number of times they have not been in each other seen in the Non Occupying dates. So we can see that the values [2021-08-15 07:49:00', '2021-08-15 07:49:02', '2021-08-15 07:51:15', '2021-08-15 07:51:34'] are in both arrays so the initial and end would be shown as 2021-08-15 07:49:02 - 2021-08-15 07:51:34 in the Occupying dates. How would I be able to do such a thing and get the Expected Output?

from datetime import datetime
import numpy as np 
import pandas as pd 

dates = ['2021-08-15 03:16:34', '2021-08-15 03:17:24', '2021-08-15 03:20:02', '2021-08-15 05:56:17', '2021-08-15 05:57:01', '2021-08-15 07:49:00', '2021-08-15 07:49:02', '2021-08-15 07:51:15', '2021-08-15 07:51:34', '2021-08-15 08:33:39']
selected_dates= ['2021-08-15 03:16:34', '2021-08-15 03:17:24', '2021-08-15 07:49:02', '2021-08-15 07:51:15', '2021-08-15 07:51:34']

Expected Output

Occupying dates: 
2021-08-15 03:16:34 - 2021-08-15 03:17:24 ​
2021-08-15 07:49:02 - 2021-08-15 07:51:34
Non Occupying dates:
2021-08-15 03:20:02 - 2021-08-15 05:57:01
2021-08-15 08:33:39
1 Answers

You can use sets for that (I've used some redundant code so you can see what's happening)

dates = ['2021-08-15 03:16:34', '2021-08-15 03:17:24', '2021-08-15 03:20:02', '2021-08-15 05:56:17', '2021-08-15 05:57:01', '2021-08-15 07:49:00', '2021-08-15 07:49:02', '2021-08-15 07:51:15', '2021-08-15 07:51:34', '2021-08-15 08:33:39']
selected_dates= ['2021-08-15 03:16:34', '2021-08-15 03:17:24', '2021-08-15 07:49:02', '2021-08-15 07:51:15', '2021-08-15 07:51:34']

found_in_both = set(dates).intersection(set(selected_dates))
found_only_once = set(dates).symmetric_difference(set(selected_dates))

Since the ordering is important for what you want, we can sort it out:

found_in_both = sorted(set(dates).intersection(set(selected_dates)))
found_only_once = sorted(set(dates).symmetric_difference(set(selected_dates)))

Now to just print your desired result format:

def print_date_list(date_list):
    for evens, odds in zip(date_list[::2], date_list[1::2]):
        print(evens, '-', odds)

    if len(date_list) % 2 == 1:
        print(date_list[-1])

print_date_list(found_in_both)
print_date_list(found_only_once)

Console output:

>>> print_date_list(found_in_both)
2021-08-15 03:16:34 - 2021-08-15 03:17:24
2021-08-15 07:49:02 - 2021-08-15 07:51:15
2021-08-15 07:51:34
>>> print_date_list(found_only_once)
2021-08-15 03:20:02 - 2021-08-15 05:56:17
2021-08-15 05:57:01 - 2021-08-15 07:49:00
2021-08-15 08:33:39
Related