Coverage for harbor_cli/output/formatting/dates.py: 80%
17 statements
« prev ^ index » next coverage.py v6.5.0, created at 2023-02-09 12:09 +0100
« prev ^ index » next coverage.py v6.5.0, created at 2023-02-09 12:09 +0100
1from __future__ import annotations
3from datetime import datetime
5from .constants import NONE_STR
8def datetime_str(
9 d: datetime | int | float | None, with_time: bool = True, subsecond: bool = False
10) -> str:
11 """Formats an optional datetime object as as a string.
13 Parameters
14 ----------
15 d : datetime | None
16 The datetime object to format.
17 with_time : bool, optional
18 Whether to include the time in the formatted string, by default True
19 subsecond : bool, optional
20 Whether to include subsecond precision in the formatted string, by default False
21 Has no effect if `with_time` is False.
22 """
23 if d is None:
24 return NONE_STR
25 if isinstance(d, (int, float)): 25 ↛ 26line 25 didn't jump to line 26, because the condition on line 25 was never true
26 try:
27 d = datetime.fromtimestamp(d)
28 except ValueError:
29 return NONE_STR
30 fmt = "%Y-%m-%d"
31 if with_time:
32 fmt = f"{fmt} %H:%M:%S"
33 if subsecond:
34 fmt = f"{fmt}.%f"
35 return d.strftime(fmt)