here a more generic approach if you need to round time up and down:
from datetime import time, datetime, timedelta
def round_time(source: time, minutes: int, floor: bool = True) -> time:
source = datetime(year=2021, month=1, day=1, hour=source.hour, minute=source.minute)
result = source + (datetime.min - source) % timedelta(minutes=minutes)
if floor and source != result:
return (result - timedelta(minutes=minutes)).time()
return result.time()
Test:
import pandas as pd
import pytest
from mpo.model.helper import round_time
time_format = "%d.%m.%Y %H:%M"
@pytest.mark.parametrize(
"testname, source_time, expected_time, minutes, floor",
[
("no round f on round", "01.01.2021 12:00", "01.01.2021 12:00", 30, True),
("no round c on round", "01.01.2021 12:00", "01.01.2021 12:00", 30, False),
("round f hh", "01.01.2021 12:45", "01.01.2021 12:30", 30, True),
("round c hh", "01.01.2021 12:45", "01.01.2021 13:00", 30, False),
("round f 1h", "01.01.2021 12:30", "01.01.2021 12:00", 60, True),
("round c 1h", "01.01.2021 12:30", "01.01.2021 13:00", 60, False),
("round c epex", "01.01.2021 09:20", "01.01.2021 09:00", 60, True),
("round c nord", "01.01.2021 09:50", "01.01.2021 09:00", 60, True),
("round c epex", "01.01.2021 09:20", "01.01.2021 10:00", 60, False),
("round c nord", "01.01.2021 09:50", "01.01.2021 10:00", 60, False),
],
)
def test_round_time(testname, source_time, expected_time, minutes, floor):
source = pd.to_datetime(source_time, format=time_format).time()
expect = pd.to_datetime(expected_time, format=time_format).time()
result = round_time(source=source, minutes=minutes, floor=floor)
assert result == expect