Skip to content

Commit

Permalink
Defer importing datetime to improve startup speed
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Feb 14, 2025
1 parent a85c171 commit aaef964
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/humanize/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from __future__ import annotations

import datetime as dt
from enum import Enum
from functools import total_ordering

Expand All @@ -15,6 +14,7 @@

TYPE_CHECKING = False
if TYPE_CHECKING:
import datetime as dt
from collections.abc import Iterable
from typing import Any

Expand Down Expand Up @@ -45,6 +45,8 @@ def __lt__(self, other: Any) -> Any:


def _now() -> dt.datetime:
import datetime as dt

return dt.datetime.now()


Expand All @@ -68,6 +70,8 @@ def _date_and_delta(value: Any, *, now: dt.datetime | None = None) -> tuple[Any,
If that's not possible, return `(None, value)`.
"""
import datetime as dt

if not now:
now = _now()
if isinstance(value, dt.datetime):
Expand Down Expand Up @@ -122,6 +126,8 @@ def naturaldelta(
assert naturaldelta(later - now) == "30 minutes"
"""
import datetime as dt

tmp = Unit[minimum_unit.upper()]
if tmp not in (Unit.SECONDS, Unit.MILLISECONDS, Unit.MICROSECONDS):
msg = f"Minimum unit '{minimum_unit}' not supported"
Expand Down Expand Up @@ -245,6 +251,8 @@ def naturaltime(
Returns:
str: A natural representation of the input in a resolution that makes sense.
"""
import datetime as dt

value = _convert_aware_datetime(value)
when = _convert_aware_datetime(when)

Expand All @@ -270,6 +278,8 @@ def _convert_aware_datetime(
value: dt.datetime | dt.timedelta | float | None,
) -> Any:
"""Convert aware datetime to naive datetime and pass through any other type."""
import datetime as dt

if isinstance(value, dt.datetime) and value.tzinfo is not None:
value = dt.datetime.fromtimestamp(value.timestamp())
return value
Expand All @@ -283,6 +293,8 @@ def naturalday(value: dt.date | dt.datetime, format: str = "%b %d") -> str:
formatted according to `format`.
"""
import datetime as dt

try:
value = dt.date(value.year, value.month, value.day)
except AttributeError:
Expand All @@ -307,6 +319,8 @@ def naturalday(value: dt.date | dt.datetime, format: str = "%b %d") -> str:

def naturaldate(value: dt.date | dt.datetime) -> str:
"""Like `naturalday`, but append a year for dates more than ~five months away."""
import datetime as dt

try:
value = dt.date(value.year, value.month, value.day)
except AttributeError:
Expand Down

0 comments on commit aaef964

Please sign in to comment.