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)
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With