代码如下:
from typing import Union
class Hour:
MINUTES = 60
def __init__(self, s: Union[str, int] = 0, minute: int = 0):
if isinstance(s, str) and "h" in s:
self.hour, self.minute = map(int, s.split("h"))
else:
self.hour, self.minute = int(s), minute
def __str__(self):
return f"{self.hour}h{self.minute:02}"
@property
def mins(self) -> int:
if self.hour < 0:
return self.hour * self.MINUTES - self.minute
return self.hour * self.MINUTES + self.minute
@classmethod
def from_minutes(cls, value: str):
if value == 0:
return cls()
if value > 0:
hour = value // cls.MINUTES
else:
value *= -1
hour = -(value // cls.MINUTES)
minute = value % cls.MINUTES
return cls(hour, minute)
def __add__(self, other):
return self.from_minutes(self.mins + other.mins)
def __sub__(self, other):
return self.from_minutes(self.mins - other.mins)
def main():
assert str(Hour("10h00") - Hour("5h00")) == "5h00"
print(
Hour("3h30"),
"-",
Hour("10h00"),
"=",
Hour("3h30") - Hour("10h00"),
' # expected: "-6h30"',
)
print('"1h00" - "2h00" = "-1h00"')
print(Hour("1h00") - Hour("2h00"))
print(Hour("1h00") - Hour("-2h00"), " # expected: 3h00")
print(Hour("1h30") - Hour("-2h00"), " # expected: 3h30")
print(Hour("-1h00") - Hour("2h00"), " # expected: -3h00")
print(Hour("-1h30") - Hour("-2h00"), " # expected: 0h30")
print(Hour("-1h30") + Hour("0h30"))
if __name__ == "__main__":
main()