-
Notifications
You must be signed in to change notification settings - Fork 148
/
time.py
630 lines (500 loc) · 19.3 KB
/
time.py
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
#!/usr/bin/env python
"""Time humanizing functions.
These are largely borrowed from Django's `contrib.humanize`.
"""
import datetime as dt
import math
import warnings
from enum import Enum, EnumMeta
from functools import total_ordering
from .i18n import _gettext as _
from .i18n import _ngettext
__all__ = [
"naturaldelta",
"naturaltime",
"naturalday",
"naturaldate",
"precisedelta",
]
@total_ordering
class _Unit(Enum):
MICROSECONDS = 0
MILLISECONDS = 1
SECONDS = 2
MINUTES = 3
HOURS = 4
DAYS = 5
MONTHS = 6
YEARS = 7
def __lt__(self, other):
if self.__class__ is other.__class__:
return self.value < other.value
return NotImplemented
class _UnitMeta(EnumMeta):
"""Metaclass for an enum that emits deprecation warnings when accessed."""
def __getattribute__(self, name):
# Temporarily comment out to avoid warning during 'import humanize'
# warnings.warn(
# "`Unit` has been deprecated. "
# "The enum is still available as the private member `_Unit`.",
# DeprecationWarning,
# )
return EnumMeta.__getattribute__(_Unit, name)
def __getitem__(cls, name):
warnings.warn(
"`Unit` has been deprecated. "
"The enum is still available as the private member `_Unit`.",
DeprecationWarning,
)
return _Unit.__getitem__(name)
def __call__(
cls, value, names=None, *, module=None, qualname=None, type=None, start=1
):
warnings.warn(
"`Unit` has been deprecated. "
"The enum is still available as the private member `_Unit`.",
DeprecationWarning,
)
return _Unit.__call__(
value, names, module=module, qualname=qualname, type=type, start=start
)
class Unit(Enum, metaclass=_UnitMeta):
# Temporary alias for _Unit to allow backwards-compatible usage.
pass
def _now():
return dt.datetime.now()
def _abs_timedelta(delta):
"""Return an "absolute" value for a timedelta, always representing a time distance.
Args:
delta (datetime.timedelta): Input timedelta.
Returns:
datetime.timedelta: Absolute timedelta.
"""
if delta.days < 0:
now = _now()
return now - (now + delta)
return delta
def abs_timedelta(delta):
"""Return an "absolute" value for a timedelta, always representing a time distance.
Args:
delta (datetime.timedelta): Input timedelta.
Returns:
datetime.timedelta: Absolute timedelta.
WARNING: This function has been deprecated. It is still available as the private
member `_abs_timedelta`.
"""
warnings.warn(
"`abs_timedelta` has been deprecated. "
"It is still available as the private member `_abs_timedelta`.",
DeprecationWarning,
)
return _abs_timedelta(delta)
def _date_and_delta(value, *, now=None):
"""Turn a value into a date and a timedelta which represents how long ago it was.
If that's not possible, return `(None, value)`.
"""
if not now:
now = _now()
if isinstance(value, dt.datetime):
date = value
delta = now - value
elif isinstance(value, dt.timedelta):
date = now - value
delta = value
else:
try:
value = int(value)
delta = dt.timedelta(seconds=value)
date = now - delta
except (ValueError, TypeError):
return None, value
return date, _abs_timedelta(delta)
def date_and_delta(delta):
"""Turn a value into a date and a timedelta which represents how long ago it was.
If that's not possible, return `(None, value)`.
WARNING: This function has been deprecated. It is still available as the private
member `_date_and_delta`.
"""
warnings.warn(
"`date_and_delta` has been deprecated. "
"It is still available as the private member `_date_and_delta`.",
DeprecationWarning,
)
return _date_and_delta(delta)
def naturaldelta(
value,
months=True,
minimum_unit="seconds",
when=None,
) -> str:
"""Return a natural representation of a timedelta or number of seconds.
This is similar to `naturaltime`, but does not add tense to the result.
Args:
value (datetime.timedelta): A timedelta or a number of seconds.
months (bool): If `True`, then a number of months (based on 30.5 days) will be
used for fuzziness between years.
minimum_unit (str): The lowest unit that can be used.
when (datetime.datetime): Point in time relative to which _value_ is
interpreted. Defaults to the current time in the local timezone.
Deprecated in version 3.14; If you need to construct a timedelta,
do it inline as the first argument.
Returns:
str: A natural representation of the amount of time elapsed.
Examples
Compare two timestamps in a custom local timezone::
import datetime as dt
from dateutil.tz import gettz
berlin = gettz("Europe/Berlin")
now = dt.datetime.now(tz=berlin)
later = now + dt.timedelta(minutes=30)
assert naturaldelta(later, when=now) == "30 minutes"
"""
if when:
warnings.warn(
"The `when` parameter of `naturaldelta()` is deprecated and will be "
"removed in humanize 4.0. If you need to construct a timedelta, "
"do it inline as the first argument.",
DeprecationWarning,
stacklevel=2,
)
tmp = _Unit[minimum_unit.upper()]
if tmp not in (_Unit.SECONDS, _Unit.MILLISECONDS, _Unit.MICROSECONDS):
raise ValueError(f"Minimum unit '{minimum_unit}' not supported")
minimum_unit = tmp
date, delta = _date_and_delta(value, now=when)
if date is None:
return value
use_months = months
seconds = abs(delta.seconds)
days = abs(delta.days)
years = days // 365
days = days % 365
months = int(days // 30.5)
if not years and days < 1:
if seconds == 0:
if minimum_unit == _Unit.MICROSECONDS and delta.microseconds < 1000:
return (
_ngettext("%d microsecond", "%d microseconds", delta.microseconds)
% delta.microseconds
)
elif minimum_unit == _Unit.MILLISECONDS or (
minimum_unit == _Unit.MICROSECONDS
and 1000 <= delta.microseconds < 1_000_000
):
milliseconds = delta.microseconds / 1000
return (
_ngettext("%d millisecond", "%d milliseconds", milliseconds)
% milliseconds
)
return _("a moment")
elif seconds == 1:
return _("a second")
elif seconds < 60:
return _ngettext("%d second", "%d seconds", seconds) % seconds
elif 60 <= seconds < 120:
return _("a minute")
elif 120 <= seconds < 3600:
minutes = seconds // 60
return _ngettext("%d minute", "%d minutes", minutes) % minutes
elif 3600 <= seconds < 3600 * 2:
return _("an hour")
elif 3600 < seconds:
hours = seconds // 3600
return _ngettext("%d hour", "%d hours", hours) % hours
elif years == 0:
if days == 1:
return _("a day")
if not use_months:
return _ngettext("%d day", "%d days", days) % days
else:
if not months:
return _ngettext("%d day", "%d days", days) % days
elif months == 1:
return _("a month")
else:
return _ngettext("%d month", "%d months", months) % months
elif years == 1:
if not months and not days:
return _("a year")
elif not months:
return _ngettext("1 year, %d day", "1 year, %d days", days) % days
elif use_months:
if months == 1:
return _("1 year, 1 month")
else:
return (
_ngettext("1 year, %d month", "1 year, %d months", months) % months
)
else:
return _ngettext("1 year, %d day", "1 year, %d days", days) % days
else:
return _ngettext("%d year", "%d years", years) % years
def naturaltime(
value,
future=False,
months=True,
minimum_unit="seconds",
when=None,
) -> str:
"""Return a natural representation of a time in a resolution that makes sense.
This is more or less compatible with Django's `naturaltime` filter.
Args:
value (datetime.datetime, int): A `datetime` or a number of seconds.
future (bool): Ignored for `datetime`s, where the tense is always figured out
based on the current time. For integers, the return value will be past tense
by default, unless future is `True`.
months (bool): If `True`, then a number of months (based on 30.5 days) will be
used for fuzziness between years.
minimum_unit (str): The lowest unit that can be used.
when (datetime.datetime): Point in time relative to which _value_ is
interpreted. Defaults to the current time in the local timezone.
Returns:
str: A natural representation of the input in a resolution that makes sense.
"""
now = when or _now()
date, delta = _date_and_delta(value, now=now)
if date is None:
return value
# determine tense by value only if datetime/timedelta were passed
if isinstance(value, (dt.datetime, dt.timedelta)):
future = date > now
ago = _("%s from now") if future else _("%s ago")
delta = naturaldelta(delta, months, minimum_unit, when=when)
if delta == _("a moment"):
return _("now")
return ago % delta
def naturalday(value, format="%b %d") -> str:
"""Return a natural day.
For date values that are tomorrow, today or yesterday compared to
present day return representing string. Otherwise, return a string
formatted according to `format`.
"""
try:
value = dt.date(value.year, value.month, value.day)
except AttributeError:
# Passed value wasn't date-ish
return value
except (OverflowError, ValueError):
# Date arguments out of range
return value
delta = value - dt.date.today()
if delta.days == 0:
return _("today")
elif delta.days == 1:
return _("tomorrow")
elif delta.days == -1:
return _("yesterday")
return value.strftime(format)
def naturaldate(value) -> str:
"""Like `naturalday`, but append a year for dates more than ~five months away."""
try:
value = dt.date(value.year, value.month, value.day)
except AttributeError:
# Passed value wasn't date-ish
return value
except (OverflowError, ValueError):
# Date arguments out of range
return value
delta = _abs_timedelta(value - dt.date.today())
if delta.days >= 5 * 365 / 12:
return naturalday(value, "%b %d %Y")
return naturalday(value)
def _quotient_and_remainder(value, divisor, unit, minimum_unit, suppress):
"""Divide `value` by `divisor` returning the quotient and remainder.
If `unit` is `minimum_unit`, makes the quotient a float number and the remainder
will be zero. The rational is that if `unit` is the unit of the quotient, we cannot
represent the remainder because it would require a unit smaller than the
`minimum_unit`.
>>> from humanize.time import _quotient_and_remainder, _Unit
>>> _quotient_and_remainder(36, 24, _Unit.DAYS, _Unit.DAYS, [])
(1.5, 0)
If unit is in `suppress`, the quotient will be zero and the remainder will be the
initial value. The idea is that if we cannot use `unit`, we are forced to use a
lower unit so we cannot do the division.
>>> _quotient_and_remainder(36, 24, _Unit.DAYS, _Unit.HOURS, [_Unit.DAYS])
(0, 36)
In other case return quotient and remainder as `divmod` would do it.
>>> _quotient_and_remainder(36, 24, _Unit.DAYS, _Unit.HOURS, [])
(1, 12)
"""
if unit == minimum_unit:
return (value / divisor, 0)
elif unit in suppress:
return (0, value)
else:
return divmod(value, divisor)
def _carry(value1, value2, ratio, unit, min_unit, suppress):
"""Return a tuple with two values.
If the unit is in `suppress`, multiply `value1` by `ratio` and add it to `value2`
(carry to right). The idea is that if we cannot represent `value1` we need to
represent it in a lower unit.
>>> from humanize.time import _carry, _Unit
>>> _carry(2, 6, 24, _Unit.DAYS, _Unit.SECONDS, [_Unit.DAYS])
(0, 54)
If the unit is the minimum unit, `value2` is divided by `ratio` and added to
`value1` (carry to left). We assume that `value2` has a lower unit so we need to
carry it to `value1`.
>>> _carry(2, 6, 24, _Unit.DAYS, _Unit.DAYS, [])
(2.25, 0)
Otherwise, just return the same input:
>>> _carry(2, 6, 24, _Unit.DAYS, _Unit.SECONDS, [])
(2, 6)
"""
if unit == min_unit:
return (value1 + value2 / ratio, 0)
elif unit in suppress:
return (0, value2 + value1 * ratio)
else:
return (value1, value2)
def _suitable_minimum_unit(min_unit, suppress):
"""Return a minimum unit suitable that is not suppressed.
If not suppressed, return the same unit:
>>> from humanize.time import _suitable_minimum_unit, _Unit
>>> _suitable_minimum_unit(_Unit.HOURS, []).name
'HOURS'
But if suppressed, find a unit greather than the original one that is not
suppressed:
>>> _suitable_minimum_unit(_Unit.HOURS, [_Unit.HOURS]).name
'DAYS'
>>> _suitable_minimum_unit(_Unit.HOURS, [_Unit.HOURS, _Unit.DAYS]).name
'MONTHS'
"""
if min_unit in suppress:
for unit in _Unit:
if unit > min_unit and unit not in suppress:
return unit
raise ValueError(
"Minimum unit is suppressed and no suitable replacement was found"
)
return min_unit
def _suppress_lower_units(min_unit, suppress):
"""Extend suppressed units (if any) with all units lower than the minimum unit.
>>> from humanize.time import _suppress_lower_units, _Unit
>>> [x.name for x in sorted(_suppress_lower_units(_Unit.SECONDS, [_Unit.DAYS]))]
['MICROSECONDS', 'MILLISECONDS', 'DAYS']
"""
suppress = set(suppress)
for u in _Unit:
if u == min_unit:
break
suppress.add(u)
return suppress
def precisedelta(value, minimum_unit="seconds", suppress=(), format="%0.2f") -> str:
"""Return a precise representation of a timedelta.
```pycon
>>> import datetime as dt
>>> from humanize.time import precisedelta
>>> delta = dt.timedelta(seconds=3633, days=2, microseconds=123000)
>>> precisedelta(delta)
'2 days, 1 hour and 33.12 seconds'
```
A custom `format` can be specified to control how the fractional part
is represented:
```pycon
>>> precisedelta(delta, format="%0.4f")
'2 days, 1 hour and 33.1230 seconds'
```
Instead, the `minimum_unit` can be changed to have a better resolution;
the function will still readjust the unit to use the greatest of the
units that does not lose precision.
For example setting microseconds but still representing the date with milliseconds:
```pycon
>>> precisedelta(delta, minimum_unit="microseconds")
'2 days, 1 hour, 33 seconds and 123 milliseconds'
```
If desired, some units can be suppressed: you will not see them represented and the
time of the other units will be adjusted to keep representing the same timedelta:
```pycon
>>> precisedelta(delta, suppress=['days'])
'49 hours and 33.12 seconds'
```
Note that microseconds precision is lost if the seconds and all
the units below are suppressed:
```pycon
>>> delta = dt.timedelta(seconds=90, microseconds=100)
>>> precisedelta(delta, suppress=['seconds', 'milliseconds', 'microseconds'])
'1.50 minutes'
```
If the delta is too small to be represented with the minimum unit,
a value of zero will be returned:
```pycon
>>> delta = dt.timedelta(seconds=1)
>>> precisedelta(delta, minimum_unit="minutes")
'0.02 minutes'
>>> delta = dt.timedelta(seconds=0.1)
>>> precisedelta(delta, minimum_unit="minutes")
'0 minutes'
```
"""
date, delta = _date_and_delta(value)
if date is None:
return value
suppress = [_Unit[s.upper()] for s in suppress]
# Find a suitable minimum unit (it can be greater the one that the
# user gave us if it is suppressed).
min_unit = _Unit[minimum_unit.upper()]
min_unit = _suitable_minimum_unit(min_unit, suppress)
del minimum_unit
# Expand the suppressed units list/set to include all the units
# that are below the minimum unit
suppress = _suppress_lower_units(min_unit, suppress)
# handy aliases
days = delta.days
secs = delta.seconds
usecs = delta.microseconds
MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS, MONTHS, YEARS = list(
_Unit
)
# Given DAYS compute YEARS and the remainder of DAYS as follows:
# if YEARS is the minimum unit, we cannot use DAYS so
# we will use a float for YEARS and 0 for DAYS:
# years, days = years/days, 0
#
# if YEARS is suppressed, use DAYS:
# years, days = 0, days
#
# otherwise:
# years, days = divmod(years, days)
#
# The same applies for months, hours, minutes and milliseconds below
years, days = _quotient_and_remainder(days, 365, YEARS, min_unit, suppress)
months, days = _quotient_and_remainder(days, 30.5, MONTHS, min_unit, suppress)
# If DAYS is not in suppress, we can represent the days but
# if it is a suppressed unit, we need to carry it to a lower unit,
# seconds in this case.
#
# The same applies for secs and usecs below
days, secs = _carry(days, secs, 24 * 3600, DAYS, min_unit, suppress)
hours, secs = _quotient_and_remainder(secs, 3600, HOURS, min_unit, suppress)
minutes, secs = _quotient_and_remainder(secs, 60, MINUTES, min_unit, suppress)
secs, usecs = _carry(secs, usecs, 1e6, SECONDS, min_unit, suppress)
msecs, usecs = _quotient_and_remainder(
usecs, 1000, MILLISECONDS, min_unit, suppress
)
# if _unused != 0 we had lost some precision
usecs, _unused = _carry(usecs, 0, 1, MICROSECONDS, min_unit, suppress)
fmts = [
("%d year", "%d years", years),
("%d month", "%d months", months),
("%d day", "%d days", days),
("%d hour", "%d hours", hours),
("%d minute", "%d minutes", minutes),
("%d second", "%d seconds", secs),
("%d millisecond", "%d milliseconds", msecs),
("%d microsecond", "%d microseconds", usecs),
]
texts = []
for unit, fmt in zip(reversed(_Unit), fmts):
singular_txt, plural_txt, value = fmt
if value > 0 or (not texts and unit == min_unit):
fmt_txt = _ngettext(singular_txt, plural_txt, value)
if unit == min_unit and math.modf(value)[0] > 0:
fmt_txt = fmt_txt.replace("%d", format)
texts.append(fmt_txt % value)
if unit == min_unit:
break
if len(texts) == 1:
return texts[0]
head = ", ".join(texts[:-1])
tail = texts[-1]
return _("%s and %s") % (head, tail)