Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/pendulum/time.py: 30%
104 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
1from __future__ import absolute_import
3from datetime import time
4from datetime import timedelta
6import pendulum
8from .constants import SECS_PER_HOUR
9from .constants import SECS_PER_MIN
10from .constants import USECS_PER_SEC
11from .duration import AbsoluteDuration
12from .duration import Duration
13from .mixins.default import FormattableMixin
16class Time(FormattableMixin, time):
17 """
18 Represents a time instance as hour, minute, second, microsecond.
19 """
21 # String formatting
22 def __repr__(self):
23 us = ""
24 if self.microsecond:
25 us = ", {}".format(self.microsecond)
27 tzinfo = ""
28 if self.tzinfo:
29 tzinfo = ", tzinfo={}".format(repr(self.tzinfo))
31 return "{}({}, {}, {}{}{})".format(
32 self.__class__.__name__, self.hour, self.minute, self.second, us, tzinfo
33 )
35 # Comparisons
37 def closest(self, dt1, dt2):
38 """
39 Get the closest time from the instance.
41 :type dt1: Time or time
42 :type dt2: Time or time
44 :rtype: Time
45 """
46 dt1 = self.__class__(dt1.hour, dt1.minute, dt1.second, dt1.microsecond)
47 dt2 = self.__class__(dt2.hour, dt2.minute, dt2.second, dt2.microsecond)
49 if self.diff(dt1).in_seconds() < self.diff(dt2).in_seconds():
50 return dt1
52 return dt2
54 def farthest(self, dt1, dt2):
55 """
56 Get the farthest time from the instance.
58 :type dt1: Time or time
59 :type dt2: Time or time
61 :rtype: Time
62 """
63 dt1 = self.__class__(dt1.hour, dt1.minute, dt1.second, dt1.microsecond)
64 dt2 = self.__class__(dt2.hour, dt2.minute, dt2.second, dt2.microsecond)
66 if self.diff(dt1).in_seconds() > self.diff(dt2).in_seconds():
67 return dt1
69 return dt2
71 # ADDITIONS AND SUBSTRACTIONS
73 def add(self, hours=0, minutes=0, seconds=0, microseconds=0):
74 """
75 Add duration to the instance.
77 :param hours: The number of hours
78 :type hours: int
80 :param minutes: The number of minutes
81 :type minutes: int
83 :param seconds: The number of seconds
84 :type seconds: int
86 :param microseconds: The number of microseconds
87 :type microseconds: int
89 :rtype: Time
90 """
91 from .datetime import DateTime
93 return (
94 DateTime.EPOCH.at(self.hour, self.minute, self.second, self.microsecond)
95 .add(
96 hours=hours, minutes=minutes, seconds=seconds, microseconds=microseconds
97 )
98 .time()
99 )
101 def subtract(self, hours=0, minutes=0, seconds=0, microseconds=0):
102 """
103 Add duration to the instance.
105 :param hours: The number of hours
106 :type hours: int
108 :param minutes: The number of minutes
109 :type minutes: int
111 :param seconds: The number of seconds
112 :type seconds: int
114 :param microseconds: The number of microseconds
115 :type microseconds: int
117 :rtype: Time
118 """
119 from .datetime import DateTime
121 return (
122 DateTime.EPOCH.at(self.hour, self.minute, self.second, self.microsecond)
123 .subtract(
124 hours=hours, minutes=minutes, seconds=seconds, microseconds=microseconds
125 )
126 .time()
127 )
129 def add_timedelta(self, delta):
130 """
131 Add timedelta duration to the instance.
133 :param delta: The timedelta instance
134 :type delta: datetime.timedelta
136 :rtype: Time
137 """
138 if delta.days:
139 raise TypeError("Cannot add timedelta with days to Time.")
141 return self.add(seconds=delta.seconds, microseconds=delta.microseconds)
143 def subtract_timedelta(self, delta):
144 """
145 Remove timedelta duration from the instance.
147 :param delta: The timedelta instance
148 :type delta: datetime.timedelta
150 :rtype: Time
151 """
152 if delta.days:
153 raise TypeError("Cannot subtract timedelta with days to Time.")
155 return self.subtract(seconds=delta.seconds, microseconds=delta.microseconds)
157 def __add__(self, other):
158 if not isinstance(other, timedelta):
159 return NotImplemented
161 return self.add_timedelta(other)
163 def __sub__(self, other):
164 if not isinstance(other, (Time, time, timedelta)):
165 return NotImplemented
167 if isinstance(other, timedelta):
168 return self.subtract_timedelta(other)
170 if isinstance(other, time):
171 if other.tzinfo is not None:
172 raise TypeError("Cannot subtract aware times to or from Time.")
174 other = self.__class__(
175 other.hour, other.minute, other.second, other.microsecond
176 )
178 return other.diff(self, False)
180 def __rsub__(self, other):
181 if not isinstance(other, (Time, time)):
182 return NotImplemented
184 if isinstance(other, time):
185 if other.tzinfo is not None:
186 raise TypeError("Cannot subtract aware times to or from Time.")
188 other = self.__class__(
189 other.hour, other.minute, other.second, other.microsecond
190 )
192 return other.__sub__(self)
194 # DIFFERENCES
196 def diff(self, dt=None, abs=True):
197 """
198 Returns the difference between two Time objects as an Duration.
200 :type dt: Time or None
202 :param abs: Whether to return an absolute interval or not
203 :type abs: bool
205 :rtype: Duration
206 """
207 if dt is None:
208 dt = pendulum.now().time()
209 else:
210 dt = self.__class__(dt.hour, dt.minute, dt.second, dt.microsecond)
212 us1 = (
213 self.hour * SECS_PER_HOUR + self.minute * SECS_PER_MIN + self.second
214 ) * USECS_PER_SEC
216 us2 = (
217 dt.hour * SECS_PER_HOUR + dt.minute * SECS_PER_MIN + dt.second
218 ) * USECS_PER_SEC
220 klass = Duration
221 if abs:
222 klass = AbsoluteDuration
224 return klass(microseconds=us2 - us1)
226 def diff_for_humans(self, other=None, absolute=False, locale=None):
227 """
228 Get the difference in a human readable format in the current locale.
230 :type other: Time or time
232 :param absolute: removes time difference modifiers ago, after, etc
233 :type absolute: bool
235 :param locale: The locale to use for localization
236 :type locale: str
238 :rtype: str
239 """
240 is_now = other is None
242 if is_now:
243 other = pendulum.now().time()
245 diff = self.diff(other)
247 return pendulum.format_diff(diff, is_now, absolute, locale)
249 # Compatibility methods
251 def replace(
252 self, hour=None, minute=None, second=None, microsecond=None, tzinfo=True
253 ):
254 if tzinfo is True:
255 tzinfo = self.tzinfo
257 hour = hour if hour is not None else self.hour
258 minute = minute if minute is not None else self.minute
259 second = second if second is not None else self.second
260 microsecond = microsecond if microsecond is not None else self.microsecond
262 t = super(Time, self).replace(hour, minute, second, microsecond, tzinfo=tzinfo)
263 return self.__class__(
264 t.hour, t.minute, t.second, t.microsecond, tzinfo=t.tzinfo
265 )
267 def __getnewargs__(self):
268 return (self,)
270 def _get_state(self, protocol=3):
271 tz = self.tzinfo
273 return (self.hour, self.minute, self.second, self.microsecond, tz)
275 def __reduce__(self):
276 return self.__reduce_ex__(2)
278 def __reduce_ex__(self, protocol):
279 return self.__class__, self._get_state(protocol)
282Time.min = Time(0, 0, 0)
283Time.max = Time(23, 59, 59, 999999)
284Time.resolution = Duration(microseconds=1)