Skip to content

Commit aaef964

Browse files
committed
Defer importing datetime to improve startup speed
1 parent a85c171 commit aaef964

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/humanize/time.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
from __future__ import annotations
77

8-
import datetime as dt
98
from enum import Enum
109
from functools import total_ordering
1110

@@ -15,6 +14,7 @@
1514

1615
TYPE_CHECKING = False
1716
if TYPE_CHECKING:
17+
import datetime as dt
1818
from collections.abc import Iterable
1919
from typing import Any
2020

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

4646

4747
def _now() -> dt.datetime:
48+
import datetime as dt
49+
4850
return dt.datetime.now()
4951

5052

@@ -68,6 +70,8 @@ def _date_and_delta(value: Any, *, now: dt.datetime | None = None) -> tuple[Any,
6870
6971
If that's not possible, return `(None, value)`.
7072
"""
73+
import datetime as dt
74+
7175
if not now:
7276
now = _now()
7377
if isinstance(value, dt.datetime):
@@ -122,6 +126,8 @@ def naturaldelta(
122126
123127
assert naturaldelta(later - now) == "30 minutes"
124128
"""
129+
import datetime as dt
130+
125131
tmp = Unit[minimum_unit.upper()]
126132
if tmp not in (Unit.SECONDS, Unit.MILLISECONDS, Unit.MICROSECONDS):
127133
msg = f"Minimum unit '{minimum_unit}' not supported"
@@ -245,6 +251,8 @@ def naturaltime(
245251
Returns:
246252
str: A natural representation of the input in a resolution that makes sense.
247253
"""
254+
import datetime as dt
255+
248256
value = _convert_aware_datetime(value)
249257
when = _convert_aware_datetime(when)
250258

@@ -270,6 +278,8 @@ def _convert_aware_datetime(
270278
value: dt.datetime | dt.timedelta | float | None,
271279
) -> Any:
272280
"""Convert aware datetime to naive datetime and pass through any other type."""
281+
import datetime as dt
282+
273283
if isinstance(value, dt.datetime) and value.tzinfo is not None:
274284
value = dt.datetime.fromtimestamp(value.timestamp())
275285
return value
@@ -283,6 +293,8 @@ def naturalday(value: dt.date | dt.datetime, format: str = "%b %d") -> str:
283293
formatted according to `format`.
284294
285295
"""
296+
import datetime as dt
297+
286298
try:
287299
value = dt.date(value.year, value.month, value.day)
288300
except AttributeError:
@@ -307,6 +319,8 @@ def naturalday(value: dt.date | dt.datetime, format: str = "%b %d") -> str:
307319

308320
def naturaldate(value: dt.date | dt.datetime) -> str:
309321
"""Like `naturalday`, but append a year for dates more than ~five months away."""
322+
import datetime as dt
323+
310324
try:
311325
value = dt.date(value.year, value.month, value.day)
312326
except AttributeError:

0 commit comments

Comments
 (0)