python-utils 4.2.0__tar.gz → 4.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. {python_utils-4.2.0 → python_utils-4.2.2}/PKG-INFO +2 -1
  2. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_import.py +103 -0
  3. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_time.py +132 -0
  4. {python_utils-4.2.0 → python_utils-4.2.2}/pyproject.toml +3 -1
  5. {python_utils-4.2.0 → python_utils-4.2.2}/pyproject.toml.orig +5 -1
  6. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/import_.py +37 -17
  7. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/time.py +47 -17
  8. {python_utils-4.2.0 → python_utils-4.2.2}/LICENSE +0 -0
  9. {python_utils-4.2.0 → python_utils-4.2.2}/README.md +0 -0
  10. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/__init__.py +0 -0
  11. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/clock.py +0 -0
  12. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_aio.py +0 -0
  13. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_aliases.py +0 -0
  14. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_containers.py +0 -0
  15. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_converters.py +0 -0
  16. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_decorators.py +0 -0
  17. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_formatters.py +0 -0
  18. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_generators.py +0 -0
  19. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_import_footprint.py +0 -0
  20. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_lazy_imports.py +0 -0
  21. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_logged.py +0 -0
  22. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_logger.py +0 -0
  23. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_python_utils.py +0 -0
  24. {python_utils-4.2.0 → python_utils-4.2.2}/_python_utils_tests/test_types.py +0 -0
  25. {python_utils-4.2.0 → python_utils-4.2.2}/conftest.py +0 -0
  26. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/__about__.py +0 -0
  27. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/__init__.py +0 -0
  28. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/_aliases.py +0 -0
  29. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/aio.py +0 -0
  30. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/containers.py +0 -0
  31. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/converters.py +0 -0
  32. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/decorators.py +0 -0
  33. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/exceptions.py +0 -0
  34. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/formatters.py +0 -0
  35. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/generators.py +0 -0
  36. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/logger.py +0 -0
  37. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/loguru.py +0 -0
  38. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/py.typed +0 -0
  39. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/terminal.py +0 -0
  40. {python_utils-4.2.0 → python_utils-4.2.2}/python_utils/types.py +0 -0
  41. {python_utils-4.2.0 → python_utils-4.2.2}/tox.ini +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-utils
3
- Version: 4.2.0
3
+ Version: 4.2.2
4
4
  Summary: Python Utils is a module with some convenient utilities not included with the standard Python install
5
5
  Keywords: utils,utilities,helpers,typing,typed,async,lazy-imports
6
6
  Author: Rick van Hattem
@@ -37,6 +37,7 @@ Project-URL: Documentation, https://python-utils.readthedocs.io/
37
37
  Project-URL: Repository, https://github.com/WoLpH/python-utils
38
38
  Project-URL: Changelog, https://github.com/WoLpH/python-utils/releases
39
39
  Project-URL: Funding, https://github.com/sponsors/wolph
40
+ Project-URL: Issues, https://github.com/wolph/python-utils/issues
40
41
  Provides-Extra: docs
41
42
  Provides-Extra: loguru
42
43
  Provides-Extra: tests
@@ -299,3 +299,106 @@ def test_import_global_requested_name_needs_an_export(
299
299
  import_.import_global(module_name, ['eggs'], locals_={}, globals_=scope)
300
300
  assert scope == {}
301
301
  assert 'eggs' not in calls
302
+
303
+
304
+ @pytest.fixture
305
+ def deep_package(
306
+ tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
307
+ ) -> collections.abc.Iterator[str]:
308
+ """Create ``testrel.nested.deeper`` with importable helper modules."""
309
+ package: pathlib.Path = tmp_path / 'testrel'
310
+ nested: pathlib.Path = package / 'nested'
311
+ deeper: pathlib.Path = nested / 'deeper'
312
+ deeper.mkdir(parents=True)
313
+ (package / '__init__.py').write_text('', encoding='utf-8')
314
+ (nested / '__init__.py').write_text('', encoding='utf-8')
315
+ (deeper / '__init__.py').write_text('', encoding='utf-8')
316
+ (package / 'helper.py').write_text('value = 42\n', encoding='utf-8')
317
+ (nested / 'inner.py').write_text(
318
+ "inner_value = 'inner'\n", encoding='utf-8'
319
+ )
320
+ monkeypatch.setattr(sys, 'path', [str(tmp_path), *sys.path])
321
+
322
+ yield 'testrel'
323
+
324
+ imported: list[str] = [
325
+ name for name in sys.modules if name.split('.')[0] == 'testrel'
326
+ ]
327
+ for name in imported:
328
+ del sys.modules[name]
329
+
330
+
331
+ def test_import_globals_relative_import_two_dots(deep_package: str) -> None:
332
+ """Resolve ``..helper`` two levels up, to ``testrel.helper`` (#73)."""
333
+ locals_: types.Dict[str, types.Any] = {}
334
+ globals_: types.Dict[str, types.Any] = {'__package__': 'testrel.nested'}
335
+ import_.import_global('..helper', locals_=locals_, globals_=globals_)
336
+ assert globals_['value'] == 42
337
+
338
+
339
+ def test_import_globals_relative_import_three_dots(deep_package: str) -> None:
340
+ """Resolve ``...helper`` three levels up, to ``testrel.helper`` (#73)."""
341
+ locals_: types.Dict[str, types.Any] = {}
342
+ globals_: types.Dict[str, types.Any] = {
343
+ '__package__': 'testrel.nested.deeper'
344
+ }
345
+ import_.import_global('...helper', locals_=locals_, globals_=globals_)
346
+ assert globals_['value'] == 42
347
+
348
+
349
+ def test_import_globals_relative_import_one_dot(deep_package: str) -> None:
350
+ """Keep resolving a single leading dot one level up (#73 control)."""
351
+ locals_: types.Dict[str, types.Any] = {}
352
+ globals_: types.Dict[str, types.Any] = {'__package__': 'testrel.nested'}
353
+ import_.import_global('.inner', locals_=locals_, globals_=globals_)
354
+ assert globals_['inner_value'] == 'inner'
355
+
356
+
357
+ def test_import_globals_relative_import_dots_only(deep_package: str) -> None:
358
+ """Reject a dots-only name, which names no module to import (#73)."""
359
+ locals_: types.Dict[str, types.Any] = {}
360
+ globals_: types.Dict[str, types.Any] = {'__package__': 'testrel.nested'}
361
+ with pytest.raises(ImportError):
362
+ import_.import_global('..', locals_=locals_, globals_=globals_)
363
+
364
+
365
+ def test_import_globals_relative_import_dots_only_exception(
366
+ deep_package: str,
367
+ ) -> None:
368
+ """Keep raising ModuleNotFoundError for a dots-only name, as 4.2.0 did."""
369
+ globals_: types.Dict[str, types.Any] = {
370
+ '__package__': 'testrel.nested.deeper'
371
+ }
372
+ error = import_.import_global(
373
+ '...',
374
+ exceptions=ModuleNotFoundError,
375
+ locals_={},
376
+ globals_=globals_,
377
+ )
378
+ assert isinstance(error, ModuleNotFoundError)
379
+
380
+
381
+ def test_import_globals_relative_import_beyond_top_level(
382
+ deep_package: str,
383
+ ) -> None:
384
+ """Raise ModuleNotFoundError above the top-level package, as 4.2.0 did."""
385
+ globals_: types.Dict[str, types.Any] = {
386
+ '__package__': 'testrel.nested.deeper'
387
+ }
388
+ with pytest.raises(ModuleNotFoundError, match='beyond top-level'):
389
+ import_.import_global('....helper', locals_={}, globals_=globals_)
390
+
391
+
392
+ def test_import_globals_empty_name() -> None:
393
+ """Keep raising IndexError for an empty name, as 4.2.0 did."""
394
+ with pytest.raises(IndexError):
395
+ import_.import_global('', locals_={}, globals_={'__package__': ''})
396
+
397
+
398
+ def test_import_globals_relative_import_trailing_dot(
399
+ deep_package: str,
400
+ ) -> None:
401
+ """Raise ModuleNotFoundError for ``..helper.``, as 4.2.0 did."""
402
+ globals_: types.Dict[str, types.Any] = {'__package__': 'testrel.nested'}
403
+ with pytest.raises(ModuleNotFoundError):
404
+ import_.import_global('..helper.', locals_={}, globals_=globals_)
@@ -4,6 +4,7 @@ import asyncio
4
4
  import datetime
5
5
  import itertools
6
6
  import time
7
+ from types import SimpleNamespace
7
8
 
8
9
  import pytest
9
10
 
@@ -465,6 +466,137 @@ def test_format_time_extreme_timedeltas() -> None:
465
466
  assert smallest == '-999999999 days, 0:00:00'
466
467
 
467
468
 
469
+ @pytest.mark.parametrize(
470
+ 'value,precision,expected',
471
+ [
472
+ (
473
+ datetime.datetime(1960, 1, 2, 3, 4, 5, 678901),
474
+ datetime.timedelta(seconds=1),
475
+ '1960-01-02 03:04:05',
476
+ ),
477
+ (
478
+ datetime.datetime(1900, 1, 2, 3, 4, 5, 678901),
479
+ datetime.timedelta(milliseconds=10),
480
+ '1900-01-02 03:04:05.670000',
481
+ ),
482
+ (
483
+ datetime.datetime.min,
484
+ datetime.timedelta(seconds=1),
485
+ '0001-01-01 00:00:00',
486
+ ),
487
+ (
488
+ datetime.datetime.max,
489
+ datetime.timedelta(seconds=1),
490
+ '9999-12-31 23:59:59',
491
+ ),
492
+ ],
493
+ )
494
+ def test_format_time_outside_platform_timestamp_range(
495
+ value: datetime.datetime,
496
+ precision: datetime.timedelta,
497
+ expected: str,
498
+ ) -> None:
499
+ """Format valid naive dates outside the platform's timestamp range."""
500
+ assert python_utils.format_time(value, precision) == expected
501
+
502
+
503
+ class _NoTimestamp(datetime.datetime):
504
+ """A datetime whose platform cannot give it a timestamp."""
505
+
506
+ def timestamp(self) -> float:
507
+ """Fail the way an out-of-range platform conversion does."""
508
+ raise ValueError('year 0 is out of range')
509
+
510
+
511
+ @pytest.mark.parametrize(
512
+ 'precision',
513
+ [datetime.timedelta(0), 1, datetime.timedelta(days=999_999_999)],
514
+ )
515
+ def test_format_time_keeps_timestamp_error_without_wall_clock(
516
+ precision: datetime.timedelta,
517
+ ) -> None:
518
+ """Raise the 4.2.1 error when exact arithmetic cannot help either."""
519
+ with pytest.raises(ValueError, match='year 0 is out of range'):
520
+ python_utils.format_time(_NoTimestamp(1, 1, 1), precision)
521
+
522
+
523
+ def test_format_time_keeps_timestamp_error_for_subclasses() -> None:
524
+ """A subclass that cannot give a timestamp raises, as in 4.2.1."""
525
+ with pytest.raises(ValueError, match='year 0 is out of range'):
526
+ python_utils.format_time(_NoTimestamp(1, 1, 1))
527
+
528
+
529
+ def test_format_time_keeps_timestamp_error_for_aware() -> None:
530
+ """Aware datetimes without a timestamp raise, as in 4.2.1."""
531
+ value = _NoTimestamp(2000, 1, 1, tzinfo=datetime.timezone.utc)
532
+ with pytest.raises(ValueError, match='year 0 is out of range'):
533
+ python_utils.format_time(value)
534
+
535
+
536
+ def test_format_time_keeps_max_when_wall_clock_overflows(
537
+ monkeypatch: pytest.MonkeyPatch,
538
+ ) -> None:
539
+ """Return the 4.2.1 maximum when neither conversion can format it."""
540
+
541
+ class NoFromTimestamp(datetime.datetime):
542
+ """Simulate a platform unable to convert the timestamp back."""
543
+
544
+ @classmethod
545
+ def fromtimestamp(
546
+ cls, timestamp: float, tz: datetime.tzinfo | None = None
547
+ ) -> 'NoFromTimestamp':
548
+ """Reject every timestamp."""
549
+ raise ValueError('year 0 is out of range')
550
+
551
+ monkeypatch.setattr(
552
+ python_utils.time,
553
+ 'datetime',
554
+ SimpleNamespace(
555
+ datetime=NoFromTimestamp,
556
+ timedelta=datetime.timedelta,
557
+ date=datetime.date,
558
+ ),
559
+ )
560
+ value = NoFromTimestamp(1, 1, 2)
561
+ result = python_utils.format_time(value, datetime.timedelta(days=7))
562
+ assert result == str(datetime.datetime.max)
563
+
564
+
565
+ @pytest.mark.parametrize('error', [OverflowError, OSError, ValueError])
566
+ @pytest.mark.parametrize('tzinfo', [None, datetime.timezone.utc])
567
+ def test_format_time_unavailable_fromtimestamp(
568
+ monkeypatch: pytest.MonkeyPatch,
569
+ error: type[Exception],
570
+ tzinfo: datetime.tzinfo | None,
571
+ ) -> None:
572
+ """Handle platform conversion failures on systems with a wider range."""
573
+
574
+ class LimitedDatetime(datetime.datetime):
575
+ """Simulate a platform unable to convert the timestamp back."""
576
+
577
+ @classmethod
578
+ def fromtimestamp(
579
+ cls, timestamp: float, tz: datetime.tzinfo | None = None
580
+ ) -> 'LimitedDatetime':
581
+ """Reject dates outside the simulated platform range."""
582
+ raise error('timestamp out of range')
583
+
584
+ value = LimitedDatetime(2000, 1, 2, 3, 4, 5, 678901, tzinfo=tzinfo)
585
+ monkeypatch.setattr(
586
+ python_utils.time,
587
+ 'datetime',
588
+ SimpleNamespace(
589
+ datetime=LimitedDatetime,
590
+ timedelta=datetime.timedelta,
591
+ date=datetime.date,
592
+ ),
593
+ )
594
+ expected = (
595
+ '2000-01-02 03:04:05' if tzinfo is None else str(datetime.datetime.max)
596
+ )
597
+ assert python_utils.format_time(value) == expected
598
+
599
+
468
600
  @pytest.mark.parametrize(
469
601
  'delta',
470
602
  [
@@ -70,6 +70,7 @@ doctest_optionflags = [
70
70
  "ALLOW_BYTES",
71
71
  ]
72
72
  asyncio_mode = "strict"
73
+ asyncio_default_fixture_loop_scope = "function"
73
74
  xfail_strict = true
74
75
  filterwarnings = [
75
76
  "error",
@@ -125,7 +126,7 @@ source-include = [
125
126
 
126
127
  [project]
127
128
  name = "python-utils"
128
- version = "4.2.0"
129
+ version = "4.2.2"
129
130
  description = "Python Utils is a module with some convenient utilities not included with the standard Python install"
130
131
  readme = "README.md"
131
132
  requires-python = ">=3.10"
@@ -168,6 +169,7 @@ Documentation = "https://python-utils.readthedocs.io/"
168
169
  Repository = "https://github.com/WoLpH/python-utils"
169
170
  Changelog = "https://github.com/WoLpH/python-utils/releases"
170
171
  Funding = "https://github.com/sponsors/wolph"
172
+ Issues = "https://github.com/wolph/python-utils/issues"
171
173
 
172
174
  [project.optional-dependencies]
173
175
  loguru = ["loguru"]
@@ -12,7 +12,7 @@ source-include = ['_python_utils_tests/**/*.py', 'conftest.py', 'tox.ini']
12
12
 
13
13
  [project]
14
14
  name = 'python-utils'
15
- version = "4.2.0" # static; the single source of truth. Bump via `uv version`.
15
+ version = "4.2.2" # static; the single source of truth. Bump via `uv version`.
16
16
  description = 'Python Utils is a module with some convenient utilities not included with the standard Python install'
17
17
  readme = 'README.md'
18
18
  requires-python = '>=3.10'
@@ -52,6 +52,7 @@ Documentation = 'https://python-utils.readthedocs.io/'
52
52
  Repository = 'https://github.com/WoLpH/python-utils'
53
53
  Changelog = 'https://github.com/WoLpH/python-utils/releases'
54
54
  Funding = 'https://github.com/sponsors/wolph'
55
+ Issues = 'https://github.com/wolph/python-utils/issues'
55
56
 
56
57
  [project.optional-dependencies]
57
58
  loguru = ['loguru']
@@ -124,6 +125,9 @@ addopts = [
124
125
  ]
125
126
  doctest_optionflags = ['ALLOW_UNICODE', 'ALLOW_BYTES']
126
127
  asyncio_mode = 'strict'
128
+ # pytest-asyncio 1.4 warns when this is unset, and filterwarnings turns the
129
+ # warning into an INTERNALERROR. 'function' is the scope it already used.
130
+ asyncio_default_fixture_loop_scope = 'function'
127
131
  xfail_strict = true
128
132
  filterwarnings = [
129
133
  'error',
@@ -113,24 +113,44 @@ def import_global( # noqa: C901
113
113
  globals_ = frame.f_globals
114
114
 
115
115
  try:
116
- # Relative imports are supported (from .spam import eggs)
116
+ # Relative imports are supported (from .spam import eggs). Each
117
+ # leading dot counts as one level, so ``..spam`` goes up two.
118
+ # An empty or dots-only name keeps the one-level path it had in
119
+ # 4.2.0, and with it the IndexError or ModuleNotFoundError.
120
+ multi_dot: bool = False
117
121
  if not name_parts[0]:
118
- name_parts = name_parts[1:]
119
- level = 1
120
-
121
- # raise IOError((name, level))
122
- module = __import__(
123
- name=name_parts[0] or '.',
124
- globals=globals_,
125
- locals=locals_,
126
- fromlist=name_parts[1:],
127
- level=max(level, 0),
128
- )
129
-
130
- # Make sure we get the right part of a dotted import (i.e.
131
- # spam.eggs should return eggs, not spam)
132
- for attr in name_parts[1:]:
133
- module = _get_attribute(module, attr, '.'.join(name_parts))
122
+ remainder: str = name.lstrip('.')
123
+ dots: int = len(name) - len(remainder)
124
+ if dots > 1 and remainder:
125
+ multi_dot = True
126
+ level = dots
127
+ name_parts = remainder.split('.')
128
+ else:
129
+ name_parts = name_parts[1:]
130
+ level = 1
131
+
132
+ try:
133
+ module = __import__(
134
+ name=name_parts[0] or '.',
135
+ globals=globals_,
136
+ locals=locals_,
137
+ fromlist=name_parts[1:],
138
+ level=max(level, 0),
139
+ )
140
+
141
+ # Make sure we get the right part of a dotted import (i.e.
142
+ # spam.eggs should return eggs, not spam)
143
+ for attr in name_parts[1:]:
144
+ module = _get_attribute(module, attr, '.'.join(name_parts))
145
+ except ImportError as error:
146
+ # Every multi-dot name failed with ModuleNotFoundError in
147
+ # 4.2.0. Python raises a plain ImportError for some of them,
148
+ # such as going above the top-level package, which
149
+ # `except ModuleNotFoundError` misses. The subclass is
150
+ # caught by both.
151
+ if not multi_dot or isinstance(error, ModuleNotFoundError):
152
+ raise
153
+ raise ModuleNotFoundError(str(error), name=name) from error
134
154
 
135
155
  # If no list of modules is given, autodetect from either __all__
136
156
  # or a dir() of the module
@@ -110,6 +110,49 @@ def delta_to_seconds_or_none(
110
110
  return delta_to_seconds(interval)
111
111
 
112
112
 
113
+ def _format_wall_clock(
114
+ timestamp: datetime.datetime, precision: datetime.timedelta
115
+ ) -> str | None:
116
+ """Truncate a naive datetime by exact arithmetic, None when it cannot.
117
+
118
+ Windows cannot convert pre-epoch naive dates to timestamps, and no
119
+ platform converts the datetime bounds. Wall-clock arithmetic relative
120
+ to the naive epoch handles both. Aware datetimes, subclasses (whose
121
+ own arithmetic and ``__str__`` may differ), precisions that are not a
122
+ usable timedelta and results outside the datetime range give None, so
123
+ the caller keeps the 4.2.1 outcome for them.
124
+ """
125
+ if (
126
+ type(timestamp) is not datetime.datetime
127
+ or timestamp.tzinfo is not None
128
+ ):
129
+ return None
130
+ try:
131
+ return str(timestamp - (timestamp - epoch) % precision)
132
+ except (ArithmeticError, TypeError, ValueError):
133
+ return None
134
+
135
+
136
+ def _format_datetime(
137
+ timestamp: datetime.datetime, precision: datetime.timedelta
138
+ ) -> str:
139
+ """Format a datetime even outside the platform's timestamp range."""
140
+ try:
141
+ since_epoch = datetime.timedelta(seconds=timestamp.timestamp())
142
+ seconds = (since_epoch - since_epoch % precision).total_seconds()
143
+ except (OverflowError, OSError, ValueError):
144
+ # 4.2.1 raised here, which stays the answer without a wall clock.
145
+ wall_clock: str | None = _format_wall_clock(timestamp, precision)
146
+ if wall_clock is None:
147
+ raise
148
+ return wall_clock
149
+ try:
150
+ return str(datetime.datetime.fromtimestamp(seconds))
151
+ except (OverflowError, OSError, ValueError):
152
+ wall_clock = _format_wall_clock(timestamp, precision)
153
+ return str(datetime.datetime.max) if wall_clock is None else wall_clock
154
+
155
+
113
156
  def format_time(
114
157
  timestamp: _aliases.timestamp_type,
115
158
  precision: datetime.timedelta = datetime.timedelta(seconds=1),
@@ -124,6 +167,8 @@ def format_time(
124
167
  '0:00:01'
125
168
  >>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))
126
169
  '2000-01-02 03:04:05'
170
+ >>> format_time(datetime.datetime(1900, 1, 2, 3, 4, 5))
171
+ '1900-01-02 03:04:05'
127
172
  >>> format_time(datetime.date(2000, 1, 2))
128
173
  '2000-01-02'
129
174
  >>> format_time(datetime.timedelta(seconds=3661))
@@ -152,23 +197,8 @@ def format_time(
152
197
  # whole microseconds, which keeps the modulo exact. In float seconds
153
198
  # `1.0 % 0.1` is just under 0.1 and the result drops a whole step.
154
199
  return str(timestamp - timestamp % precision)
155
- elif isinstance(timestamp, datetime.datetime): # pragma: no cover
156
- # Python 2 doesn't have the timestamp method
157
- if hasattr(timestamp, 'timestamp'):
158
- seconds = timestamp.timestamp()
159
- else:
160
- seconds = timedelta_to_seconds(timestamp - epoch)
161
-
162
- # Truncate the number to the given precision, in whole microseconds
163
- # for the same reason as above
164
- since_epoch: datetime.timedelta = datetime.timedelta(seconds=seconds)
165
- seconds = (since_epoch - since_epoch % precision).total_seconds()
166
-
167
- try: # pragma: no cover
168
- dt = datetime.datetime.fromtimestamp(seconds)
169
- except (ValueError, OSError): # pragma: no cover
170
- dt = datetime.datetime.max
171
- return str(dt)
200
+ elif isinstance(timestamp, datetime.datetime):
201
+ return _format_datetime(timestamp, precision)
172
202
  elif isinstance(timestamp, datetime.date):
173
203
  return str(timestamp)
174
204
  elif timestamp is None:
File without changes
File without changes
File without changes
File without changes