1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
|
from __future__ import absolute_import
from __future__ import division
from datetime import timedelta
import pendulum
from pendulum.utils._compat import PYPY
from pendulum.utils._compat import decode
from .constants import SECONDS_PER_DAY
from .constants import SECONDS_PER_HOUR
from .constants import SECONDS_PER_MINUTE
from .constants import US_PER_SECOND
def _divide_and_round(a, b):
"""divide a by b and round result to the nearest integer
When the ratio is exactly half-way between two integers,
the even integer is returned.
"""
# Based on the reference implementation for divmod_near
# in Objects/longobject.c.
q, r = divmod(a, b)
# round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
# The expression r / b > 0.5 is equivalent to 2 * r > b if b is
# positive, 2 * r < b if b negative.
r *= 2
greater_than_half = r > b if b > 0 else r < b
if greater_than_half or r == b and q % 2 == 1:
q += 1
return q
class Duration(timedelta):
"""
Replacement for the standard timedelta class.
Provides several improvements over the base class.
"""
_y = None
_m = None
_w = None
_d = None
_h = None
_i = None
_s = None
_invert = None
def __new__(
cls,
days=0,
seconds=0,
microseconds=0,
milliseconds=0,
minutes=0,
hours=0,
weeks=0,
years=0,
months=0,
):
if not isinstance(years, int) or not isinstance(months, int):
raise ValueError("Float year and months are not supported")
self = timedelta.__new__(
cls,
days + years * 365 + months * 30,
seconds,
microseconds,
milliseconds,
minutes,
hours,
weeks,
)
# Intuitive normalization
total = self.total_seconds() - (years * 365 + months * 30) * SECONDS_PER_DAY
self._total = total
m = 1
if total < 0:
m = -1
self._microseconds = round(total % m * 1e6)
self._seconds = abs(int(total)) % SECONDS_PER_DAY * m
_days = abs(int(total)) // SECONDS_PER_DAY * m
self._days = _days
self._remaining_days = abs(_days) % 7 * m
self._weeks = abs(_days) // 7 * m
self._months = months
self._years = years
return self
def total_minutes(self):
return self.total_seconds() / SECONDS_PER_MINUTE
def total_hours(self):
return self.total_seconds() / SECONDS_PER_HOUR
def total_days(self):
return self.total_seconds() / SECONDS_PER_DAY
def total_weeks(self):
return self.total_days() / 7
if PYPY:
def total_seconds(self):
days = 0
if hasattr(self, "_years"):
days += self._years * 365
if hasattr(self, "_months"):
days += self._months * 30
if hasattr(self, "_remaining_days"):
days += self._weeks * 7 + self._remaining_days
else:
days += self._days
return (
(days * SECONDS_PER_DAY + self._seconds) * US_PER_SECOND
+ self._microseconds
) / US_PER_SECOND
@property
def years(self):
return self._years
@property
def months(self):
return self._months
@property
def weeks(self):
return self._weeks
if PYPY:
@property
def days(self):
return self._years * 365 + self._months * 30 + self._days
@property
def remaining_days(self):
return self._remaining_days
@property
def hours(self):
if self._h is None:
seconds = self._seconds
self._h = 0
if abs(seconds) >= 3600:
self._h = (abs(seconds) // 3600 % 24) * self._sign(seconds)
return self._h
@property
def minutes(self):
if self._i is None:
seconds = self._seconds
self._i = 0
if abs(seconds) >= 60:
self._i = (abs(seconds) // 60 % 60) * self._sign(seconds)
return self._i
@property
def seconds(self):
return self._seconds
@property
def remaining_seconds(self):
if self._s is None:
self._s = self._seconds
self._s = abs(self._s) % 60 * self._sign(self._s)
return self._s
@property
def microseconds(self):
return self._microseconds
@property
def invert(self):
if self._invert is None:
self._invert = self.total_seconds() < 0
return self._invert
def in_weeks(self):
return int(self.total_weeks())
def in_days(self):
return int(self.total_days())
def in_hours(self):
return int(self.total_hours())
def in_minutes(self):
return int(self.total_minutes())
def in_seconds(self):
return int(self.total_seconds())
def in_words(self, locale=None, separator=" "):
"""
Get the current interval in words in the current locale.
Ex: 6 jours 23 heures 58 minutes
:param locale: The locale to use. Defaults to current locale.
:type locale: str
:param separator: The separator to use between each unit
:type separator: str
:rtype: str
"""
periods = [
("year", self.years),
("month", self.months),
("week", self.weeks),
("day", self.remaining_days),
("hour", self.hours),
("minute", self.minutes),
("second", self.remaining_seconds),
]
if locale is None:
locale = pendulum.get_locale()
locale = pendulum.locale(locale)
parts = []
for period in periods:
unit, count = period
if abs(count) > 0:
translation = locale.translation(
"units.{}.{}".format(unit, locale.plural(abs(count)))
)
parts.append(translation.format(count))
if not parts:
if abs(self.microseconds) > 0:
unit = "units.second.{}".format(locale.plural(1))
count = "{:.2f}".format(abs(self.microseconds) / 1e6)
else:
unit = "units.microsecond.{}".format(locale.plural(0))
count = 0
translation = locale.translation(unit)
parts.append(translation.format(count))
return decode(separator.join(parts))
def _sign(self, value):
if value < 0:
return -1
return 1
def as_timedelta(self):
"""
Return the interval as a native timedelta.
:rtype: timedelta
"""
return timedelta(seconds=self.total_seconds())
def __str__(self):
return self.in_words()
def __repr__(self):
rep = "{}(".format(self.__class__.__name__)
if self._years:
rep += "years={}, ".format(self._years)
if self._months:
rep += "months={}, ".format(self._months)
if self._weeks:
rep += "weeks={}, ".format(self._weeks)
if self._days:
rep += "days={}, ".format(self._remaining_days)
if self.hours:
rep += "hours={}, ".format(self.hours)
if self.minutes:
rep += "minutes={}, ".format(self.minutes)
if self.remaining_seconds:
rep += "seconds={}, ".format(self.remaining_seconds)
if self.microseconds:
rep += "microseconds={}, ".format(self.microseconds)
rep += ")"
return rep.replace(", )", ")")
def __add__(self, other):
if isinstance(other, timedelta):
return self.__class__(seconds=self.total_seconds() + other.total_seconds())
return NotImplemented
__radd__ = __add__
def __sub__(self, other):
if isinstance(other, timedelta):
return self.__class__(seconds=self.total_seconds() - other.total_seconds())
return NotImplemented
def __neg__(self):
return self.__class__(
years=-self._years,
months=-self._months,
weeks=-self._weeks,
days=-self._remaining_days,
seconds=-self._seconds,
microseconds=-self._microseconds,
)
def _to_microseconds(self):
return (self._days * (24 * 3600) + self._seconds) * 1000000 + self._microseconds
def __mul__(self, other):
if isinstance(other, int):
return self.__class__(
years=self._years * other,
months=self._months * other,
seconds=self._total * other,
)
if isinstance(other, float):
usec = self._to_microseconds()
a, b = other.as_integer_ratio()
return self.__class__(0, 0, _divide_and_round(usec * a, b))
return NotImplemented
__rmul__ = __mul__
def __floordiv__(self, other):
if not isinstance(other, (int, timedelta)):
return NotImplemented
usec = self._to_microseconds()
if isinstance(other, timedelta):
return usec // other._to_microseconds()
if isinstance(other, int):
return self.__class__(
0,
0,
usec // other,
years=self._years // other,
months=self._months // other,
)
def __truediv__(self, other):
if not isinstance(other, (int, float, timedelta)):
return NotImplemented
usec = self._to_microseconds()
if isinstance(other, timedelta):
return usec / other._to_microseconds()
if isinstance(other, int):
return self.__class__(
0,
0,
_divide_and_round(usec, other),
years=_divide_and_round(self._years, other),
months=_divide_and_round(self._months, other),
)
if isinstance(other, float):
a, b = other.as_integer_ratio()
return self.__class__(
0,
0,
_divide_and_round(b * usec, a),
years=_divide_and_round(self._years * b, a),
months=_divide_and_round(self._months, other),
)
__div__ = __floordiv__
def __mod__(self, other):
if isinstance(other, timedelta):
r = self._to_microseconds() % other._to_microseconds()
return self.__class__(0, 0, r)
return NotImplemented
def __divmod__(self, other):
if isinstance(other, timedelta):
q, r = divmod(self._to_microseconds(), other._to_microseconds())
return q, self.__class__(0, 0, r)
return NotImplemented
Duration.min = Duration(days=-999999999)
Duration.max = Duration(
days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999
)
Duration.resolution = Duration(microseconds=1)
class AbsoluteDuration(Duration):
"""
Duration that expresses a time difference in absolute values.
"""
def __new__(
cls,
days=0,
seconds=0,
microseconds=0,
milliseconds=0,
minutes=0,
hours=0,
weeks=0,
years=0,
months=0,
):
if not isinstance(years, int) or not isinstance(months, int):
raise ValueError("Float year and months are not supported")
self = timedelta.__new__(
cls, days, seconds, microseconds, milliseconds, minutes, hours, weeks
)
# We need to compute the total_seconds() value
# on a native timedelta object
delta = timedelta(
days, seconds, microseconds, milliseconds, minutes, hours, weeks
)
# Intuitive normalization
self._total = delta.total_seconds()
total = abs(self._total)
self._microseconds = round(total % 1 * 1e6)
self._seconds = int(total) % SECONDS_PER_DAY
days = int(total) // SECONDS_PER_DAY
self._days = abs(days + years * 365 + months * 30)
self._remaining_days = days % 7
self._weeks = days // 7
self._months = abs(months)
self._years = abs(years)
return self
def total_seconds(self):
return abs(self._total)
@property
def invert(self):
if self._invert is None:
self._invert = self._total < 0
return self._invert
|