Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split date range with time by day

I have a range of dates over time. Example:

diapason = ["2020-11-02 17:40", "2020-11-05 10:00"]

and I want to get such a split:

diapason = [(2020-11-02 17:40, 2020-11-03 00:00), (2020-11-03 00:00, 2020-11-04 00:00), (2020-11-04 00:00, 2020-11-05 00:00), (2020-11-05 00:00, 2020-11-05 10:00)]

How can i do this? So far, I only manage to divide by 24 hours something like this:

from datetime import datetime,timedelta
diapason = ["2020-11-02 17:40", "2020-11-05 10:00"]

start = datetime.strptime(diapason[0], "%Y-%m-%d %H:%M")
end = datetime.strptime(diapason[1], "%Y-%m-%d %H:%M")
r = [(start + timedelta(days=i)).strftime("%Y-%m-%d %H:%M:%S.%f") for i in range(0, (end-start).days, 1)]

print(r)
like image 619
De1f Avatar asked Jul 27 '26 07:07

De1f


1 Answers

Create a date range with the elements being lists, replace first and last elements with start / end datetime and format to tuples of strings:

from datetime import datetime, timedelta

diapason = ["2020-11-02 17:40", "2020-11-05 10:00"]
# diapason = ['2023-03-07 16:00:00','2023-03-14 19:00:00']

start, end = [datetime.fromisoformat(d) for d in diapason]
offset = 1 if start.time() <= end.time() else 2

output = [
    [start.date() + timedelta(d), start.date() + timedelta(d + 1)]
    for d in range((end - start).days + offset)
]

output[0][0], output[-1][-1] = start, end

output = [
    (l[0].strftime("%Y-%m-%d %H:%M"), l[1].strftime("%Y-%m-%d %H:%M")) for l in output
]

# output
# [('2020-11-02 17:40', '2020-11-03 00:00'),
#  ('2020-11-03 00:00', '2020-11-04 00:00'),
#  ('2020-11-04 00:00', '2020-11-05 00:00'),
#  ('2020-11-05 00:00', '2020-11-05 10:00')]
like image 131
FObersteiner Avatar answered Jul 28 '26 19:07

FObersteiner