Skip to content

Instantly share code, notes, and snippets.

@MaZderMind
Created April 23, 2021 06:48
Show Gist options
  • Save MaZderMind/6ed5be1d0368c0b5d4bfb61822959310 to your computer and use it in GitHub Desktop.
Save MaZderMind/6ed5be1d0368c0b5d4bfb61822959310 to your computer and use it in GitHub Desktop.
datetime_custom_rollover.py
from datetime import datetime, time, date, timedelta
def rollover(dt: datetime, rollover: time) -> date:
given_time = dt.time()
if given_time < rollover:
return dt.date()
else:
return dt.date() + timedelta(days=1)
def test_rollover():
rollover_time = time(13, 0)
# before 13:00 it's the given day
assert rollover(datetime(2021, 1, 1, 0, 0), rollover_time) == date(2021, 1, 1)
assert rollover(datetime(2021, 1, 1, 6, 0), rollover_time) == date(2021, 1, 1)
assert rollover(datetime(2021, 1, 1, 12, 0), rollover_time) == date(2021, 1, 1)
# after 13:00 it's the next day
assert rollover(datetime(2021, 1, 1, 13, 0), rollover_time) == date(2021, 1, 2)
assert rollover(datetime(2021, 1, 1, 16, 0), rollover_time) == date(2021, 1, 2)
assert rollover(datetime(2021, 1, 1, 20, 0), rollover_time) == date(2021, 1, 2)
assert rollover(datetime(2021, 1, 1, 23, 0), rollover_time) == date(2021, 1, 2)
assert rollover(datetime(2021, 1, 1, 23, 59), rollover_time) == date(2021, 1, 2)
# and it continues to be the next day until 13:00
assert rollover(datetime(2021, 1, 2, 0, 0), rollover_time) == date(2021, 1, 2)
assert rollover(datetime(2021, 1, 2, 6, 0), rollover_time) == date(2021, 1, 2)
assert rollover(datetime(2021, 1, 2, 12, 0), rollover_time) == date(2021, 1, 2)
# then it's the day after
assert rollover(datetime(2021, 1, 2, 13, 0), rollover_time) == date(2021, 1, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment