Skip to content

Time

Time humanizing functions.

These are largely borrowed from Django's contrib.humanize.

naturaldate(value)

Like naturalday, but append a year for dates more than ~five months away.

Source code in .tox/docs/lib/python3.12/site-packages/humanize/time.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def naturaldate(value: dt.date | dt.datetime) -> 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 str(value)
    except (OverflowError, ValueError):
        # Date arguments out of range
        return str(value)
    delta = _abs_timedelta(value - dt.date.today())
    if delta.days >= 5 * 365 / 12:
        return naturalday(value, "%b %d %Y")
    return naturalday(value)

naturalday(value, format='%b %d')

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.

Source code in .tox/docs/lib/python3.12/site-packages/humanize/time.py
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
def naturalday(value: dt.date | dt.datetime, format: str = "%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 str(value)
    except (OverflowError, ValueError):
        # Date arguments out of range
        return str(value)
    delta = value - dt.date.today()

    if delta.days == 0:
        return _("today")

    if delta.days == 1:
        return _("tomorrow")

    if delta.days == -1:
        return _("yesterday")

    return value.strftime(format)

naturaldelta(value, months=True, minimum_unit='seconds')

Return a natural representation of a timedelta or number of seconds.

This is similar to naturaltime, but does not add tense to the result.

Parameters:

Name Type Description Default
value (timedelta, int or float)

A timedelta or a number of seconds.

required
months bool

If True, then a number of months (based on 30.5 days) will be used for fuzziness between years.

True
minimum_unit str

The lowest unit that can be used.

'seconds'

Returns:

Name Type Description
str str or `value`

A natural representation of the amount of time elapsed unless value is not datetime.timedelta or cannot be converted to int (cannot be float due to 'inf' or 'nan'). In that case, a value is returned unchanged.

Raises:

Type Description
OverflowError

If value is too large to convert to datetime.timedelta.

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 - now) == "30 minutes"

Source code in .tox/docs/lib/python3.12/site-packages/humanize/time.py
 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
def naturaldelta(
    value: dt.timedelta | float,
    months: bool = True,
    minimum_unit: str = "seconds",
) -> 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, int or float): 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.

    Returns:
        str (str or `value`): A natural representation of the amount of time
            elapsed unless `value` is not datetime.timedelta or cannot be
            converted to int (cannot be float due to 'inf' or 'nan').
            In that case, a `value` is returned unchanged.

    Raises:
        OverflowError: If `value` is too large to convert to datetime.timedelta.

    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 - now) == "30 minutes"
    """
    tmp = Unit[minimum_unit.upper()]
    if tmp not in (Unit.SECONDS, Unit.MILLISECONDS, Unit.MICROSECONDS):
        msg = f"Minimum unit '{minimum_unit}' not supported"
        raise ValueError(msg)
    min_unit = tmp

    if isinstance(value, dt.timedelta):
        delta = value
    else:
        try:
            int(value)  # Explicitly don't support string such as "NaN" or "inf"
            value = float(value)
            delta = dt.timedelta(seconds=value)
        except (ValueError, TypeError):
            return str(value)

    use_months = months

    delta = abs(delta)
    years = delta.days // 365
    days = delta.days % 365
    num_months = int(days // 30.5)

    if not years and days < 1:
        if delta.seconds == 0:
            if min_unit == Unit.MICROSECONDS and delta.microseconds < 1000:
                return (
                    _ngettext("%d microsecond", "%d microseconds", delta.microseconds)
                    % delta.microseconds
                )

            if min_unit == Unit.MILLISECONDS or (
                min_unit == Unit.MICROSECONDS and 1000 <= delta.microseconds < 1_000_000
            ):
                milliseconds = delta.microseconds / 1000
                return (
                    _ngettext("%d millisecond", "%d milliseconds", int(milliseconds))
                    % milliseconds
                )
            return _("a moment")

        if delta.seconds == 1:
            return _("a second")

        if delta.seconds < 60:
            return _ngettext("%d second", "%d seconds", delta.seconds) % delta.seconds

        if 60 <= delta.seconds < 120:
            return _("a minute")

        if 120 <= delta.seconds < 3600:
            minutes = delta.seconds // 60
            return _ngettext("%d minute", "%d minutes", minutes) % minutes

        if 3600 <= delta.seconds < 3600 * 2:
            return _("an hour")

        if 3600 < delta.seconds:
            hours = delta.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

        if not num_months:
            return _ngettext("%d day", "%d days", days) % days

        if num_months == 1:
            return _("a month")

        return _ngettext("%d month", "%d months", num_months) % num_months

    elif years == 1:
        if not num_months and not days:
            return _("a year")

        if not num_months:
            return _ngettext("1 year, %d day", "1 year, %d days", days) % days

        if use_months:
            if num_months == 1:
                return _("1 year, 1 month")

            return (
                _ngettext("1 year, %d month", "1 year, %d months", num_months)
                % num_months
            )

        return _ngettext("1 year, %d day", "1 year, %d days", days) % days

    return _ngettext("%d year", "%d years", years).replace("%d", "%s") % intcomma(years)

naturaltime(value, future=False, months=True, minimum_unit='seconds', when=None)

Return a natural representation of a time in a resolution that makes sense.

This is more or less compatible with Django's naturaltime filter.

Parameters:

Name Type Description Default
value (datetime, timedelta, int or float)

A datetime, a timedelta, or a number of seconds.

required
future bool

Ignored for datetimes and timedeltas, where the tense is always figured out based on the current time. For integers and floats, the return value will be past tense by default, unless future is True.

False
months bool

If True, then a number of months (based on 30.5 days) will be used for fuzziness between years.

True
minimum_unit str

The lowest unit that can be used.

'seconds'
when datetime

Point in time relative to which value is interpreted. Defaults to the current time in the local timezone.

None

Returns:

Name Type Description
str str

A natural representation of the input in a resolution that makes sense.

Source code in .tox/docs/lib/python3.12/site-packages/humanize/time.py
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
def naturaltime(
    value: dt.datetime | dt.timedelta | float,
    future: bool = False,
    months: bool = True,
    minimum_unit: str = "seconds",
    when: dt.datetime | None = 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, datetime.timedelta, int or float): A `datetime`, a
            `timedelta`, or a number of seconds.
        future (bool): Ignored for `datetime`s and `timedelta`s, where the tense is
            always figured out based on the current time. For integers and floats, 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.
    """
    value = _convert_aware_datetime(value)
    when = _convert_aware_datetime(when)

    now = when or _now()

    date, delta = _date_and_delta(value, now=now)
    if date is None:
        return str(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)

    if delta == _("a moment"):
        return _("now")

    return str(ago % delta)

precisedelta(value, minimum_unit='seconds', suppress=(), format='%0.2f')

Return a precise representation of a timedelta.

>>> 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:

>>> 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:

>>> 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:

>>> 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:

>>> 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:

>>> 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'
Source code in .tox/docs/lib/python3.12/site-packages/humanize/time.py
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
def precisedelta(
    value: dt.timedelta | int | None,
    minimum_unit: str = "seconds",
    suppress: typing.Iterable[str] = (),
    format: str = "%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 str(value)

    suppress_set = {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_set)
    del minimum_unit

    # Expand the suppressed units list/set to include all the units
    # that are below the minimum unit
    suppress_set = _suppress_lower_units(min_unit, suppress_set)

    # 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_set)
    months, days = _quotient_and_remainder(days, 30.5, MONTHS, min_unit, suppress_set)

    # 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_set)

    hours, secs = _quotient_and_remainder(secs, 3600, HOURS, min_unit, suppress_set)
    minutes, secs = _quotient_and_remainder(secs, 60, MINUTES, min_unit, suppress_set)

    secs, usecs = _carry(secs, usecs, 1e6, SECONDS, min_unit, suppress_set)

    msecs, usecs = _quotient_and_remainder(
        usecs, 1000, MILLISECONDS, min_unit, suppress_set
    )

    # if _unused != 0 we had lost some precision
    usecs, _unused = _carry(usecs, 0, 1, MICROSECONDS, min_unit, suppress_set)

    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: list[str] = []
    for unit, fmt in zip(reversed(Unit), fmts):
        singular_txt, plural_txt, fmt_value = fmt
        if fmt_value > 0 or (not texts and unit == min_unit):
            _fmt_value = 2 if 1 < fmt_value < 2 else int(fmt_value)
            fmt_txt = _ngettext(singular_txt, plural_txt, _fmt_value)
            if unit == min_unit and math.modf(fmt_value)[0] > 0:
                fmt_txt = fmt_txt.replace("%d", format)
            elif unit == YEARS:
                fmt_txt = fmt_txt.replace("%d", "%s")
                texts.append(fmt_txt % intcomma(fmt_value))
                continue

            texts.append(fmt_txt % fmt_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)