Created
March 14, 2022 22:35
-
-
Save hansthen/6c81a15cd54f34fc07cb18a05ba11b34 to your computer and use it in GitHub Desktop.
Determine bins from a duration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import timedelta, datetime | |
from collections import Counter | |
def bin_days(d1, d2): | |
counter = Counter() | |
d_next = d1.replace(hour = 0, minute=0, second=0) + timedelta(days=1) | |
weekday = d1.weekday() | |
counter[weekday] += (d_next - d1).total_seconds() / (24 * 60 * 60) | |
delta = d2 - d_next | |
weeks, days = divmod(delta.days, 7) | |
for i in range(7): | |
counter[i] += weeks | |
for i in range(weekday + 1, weekday + days + 1): | |
counter[i % 7] += 1 | |
counter[(weekday + days + 1) % 7] += delta.seconds / (24 * 60 * 60) | |
return counter | |
def bin_hours(d1, d2): | |
counter = Counter() | |
h_next = d1.replace(minute=0, second=0) + timedelta(hours=1) | |
hour = d1.hour | |
counter[hour] += (h_next - d1).total_seconds() / (60 * 60) | |
delta = d2 - h_next | |
days = delta.days | |
for i in range(24): | |
counter[i] += days | |
hours, seconds = divmod(delta.seconds, 3600) | |
for i in range(hour + 1, hour + hours + 1): | |
counter[i % 24] += 1 | |
counter[(hour + hours + 1) % 24] += seconds / (60 * 60) | |
return counter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment