Debian Codegraph @

src/isoduration/types.py

raw symbols SCIP
1 from __future__ import annotations
2
3 from dataclasses import dataclass
4 from datetime import datetime
5 from decimal import Decimal
6 from typing import Iterator, Tuple
7
8 from isoduration.formatter import format_duration
9 from isoduration.operations import add
10
11
12 @dataclass
13 class DateDuration:
14 years: Decimal = Decimal(0)
15 months: Decimal = Decimal(0)
16 days: Decimal = Decimal(0)
17 weeks: Decimal = Decimal(0)
18
19 def __neg__(self) -> DateDuration:
20 return DateDuration(
21 years=-self.years,
22 months=-self.months,
23 days=-self.days,
24 weeks=-self.weeks,
25 )
26
27
28 @dataclass
29 class TimeDuration:
30 hours: Decimal = Decimal(0)
31 minutes: Decimal = Decimal(0)
32 seconds: Decimal = Decimal(0)
33
34 def __neg__(self) -> TimeDuration:
35 return TimeDuration(
36 hours=-self.hours,
37 minutes=-self.minutes,
38 seconds=-self.seconds,
39 )
40
41
42 class Duration:
43 def __init__(self, date_duration: DateDuration, time_duration: TimeDuration):
44 self.date = date_duration
45 self.time = time_duration
46
47 def __repr__(self) -> str:
48 return f"{self.__class__.__name__}({self.date}, {self.time})"
49
50 def __str__(self) -> str:
51 return format_duration(self)
52
53 def __hash__(self) -> int:
54 return hash(
55 (
56 self.date.years,
57 self.date.months,
58 self.date.days,
59 self.date.weeks,
60 self.time.hours,
61 self.time.minutes,
62 self.time.seconds,
63 )
64 )
65
66 def __eq__(self, other: object) -> bool:
67 if isinstance(other, Duration):
68 return self.date == other.date and self.time == other.time
69
70 raise NotImplementedError
71
72 def __iter__(self) -> Iterator[Tuple[str, Decimal]]:
73 time_duration = self.time
74 time_order = ("hours", "minutes", "seconds")
75
76 date_duration = self.date
77 date_order = ("years", "months", "days", "weeks")
78
79 for element in date_order:
80 yield element, getattr(date_duration, element)
81 for element in time_order:
82 yield element, getattr(time_duration, element)
83
84 def __reversed__(self) -> Iterator[Tuple[str, Decimal]]:
85 time_duration = self.time
86 time_order = ("seconds", "minutes", "hours")
87
88 date_duration = self.date
89 date_order = ("weeks", "days", "months", "years")
90
91 for element in time_order:
92 yield element, getattr(time_duration, element)
93 for element in date_order:
94 yield element, getattr(date_duration, element)
95
96 def __neg__(self) -> Duration:
97 return Duration(-self.date, -self.time)
98
99 def __add__(self, other: datetime) -> datetime:
100 if isinstance(other, datetime):
101 return add(other, self)
102
103 raise NotImplementedError
104
105 __radd__ = __add__
106
107 def __sub__(self, other: object) -> None:
108 raise NotImplementedError
109
110 def __rsub__(self, other: datetime) -> datetime:
111 if isinstance(other, datetime):
112 return -self + other
113
114 raise NotImplementedError