9
9
import collections .abc
10
10
import datetime as dt
11
11
import math
12
+ import re
12
13
import typing
13
14
from enum import Enum
14
15
from functools import total_ordering
@@ -63,7 +64,7 @@ def _abs_timedelta(delta: dt.timedelta) -> dt.timedelta:
63
64
64
65
65
66
def _date_and_delta (
66
- value : typing .Any , * , now : dt .datetime | None = None
67
+ value : typing .Any , * , now : dt .datetime | None = None , precise : bool = False
67
68
) -> tuple [typing .Any , typing .Any ]:
68
69
"""Turn a value into a date and a timedelta which represents how long ago it was.
69
70
@@ -79,7 +80,7 @@ def _date_and_delta(
79
80
delta = value
80
81
else :
81
82
try :
82
- value = int (value )
83
+ value = value if precise else int (value )
83
84
delta = dt .timedelta (seconds = value )
84
85
date = now - delta
85
86
except (ValueError , TypeError ):
@@ -414,12 +415,12 @@ def _suppress_lower_units(min_unit: Unit, suppress: typing.Iterable[Unit]) -> se
414
415
415
416
416
417
def precisedelta (
417
- value : dt .timedelta | int ,
418
+ value : dt .timedelta | float ,
418
419
minimum_unit : str = "seconds" ,
419
420
suppress : typing .Iterable [str ] = (),
420
421
format : str = "%0.2f" ,
421
422
) -> str :
422
- """Return a precise representation of a timedelta.
423
+ """Return a precise representation of a timedelta or number of seconds .
423
424
424
425
```pycon
425
426
>>> import datetime as dt
@@ -485,7 +486,7 @@ def precisedelta(
485
486
486
487
```
487
488
"""
488
- date , delta = _date_and_delta (value )
489
+ date , delta = _date_and_delta (value , precise = True )
489
490
if date is None :
490
491
return str (value )
491
492
@@ -555,9 +556,13 @@ def precisedelta(
555
556
("%d microsecond" , "%d microseconds" , usecs ),
556
557
]
557
558
559
+ round_fmt_value = re .fullmatch (r"%\d*(d|(\.0*f))" , format )
560
+
558
561
texts : list [str ] = []
559
562
for unit , fmt in zip (reversed (Unit ), fmts ):
560
563
singular_txt , plural_txt , fmt_value = fmt
564
+ if round_fmt_value :
565
+ fmt_value = round (fmt_value )
561
566
if fmt_value > 0 or (not texts and unit == min_unit ):
562
567
fmt_txt = _ngettext (singular_txt , plural_txt , fmt_value )
563
568
if unit == min_unit and math .modf (fmt_value )[0 ] > 0 :
0 commit comments