Coverage for kwai/core/domain/value_objects/time_period.py: 83%

18 statements  

« prev     ^ index     » next       coverage.py v7.3.0, created at 2023-09-05 17:55 +0000

1"""Module that defines a period between times.""" 

2 

3from dataclasses import dataclass 

4from datetime import date, datetime, time, timedelta 

5 

6 

7@dataclass(frozen=True, kw_only=True, slots=True) 

8class TimePeriod: 

9 """A period between two times.""" 

10 

11 start: time 

12 end: time | None = None 

13 

14 def __post_init__(self): 

15 """Perform post initialization. 

16 

17 Raises: 

18 ValueError: when the start time is before the end time. 

19 """ 

20 if self.end is not None: 

21 if self.start > self.end: 

22 raise ValueError("start should be before end") 

23 

24 @property 

25 def endless(self) -> bool: 

26 """Return True when the period does not have an end time.""" 

27 return self.end is None 

28 

29 @property 

30 def delta(self) -> timedelta | None: 

31 """Return the delta between end and start time. 

32 

33 Returns: The delta between the start and end time. 

34 

35 When there is no end time, the result will be None. 

36 """ 

37 if self.end is None: 

38 return None 

39 

40 return datetime.combine(date(1, 1, 1), self.end) - datetime.combine( 

41 date(1, 1, 1), self.start 

42 )