Skip to content

Commit 74c62a9

Browse files
committed
Improve error message when unable to convert to datetime
1 parent 6cb67ac commit 74c62a9

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

infrahub_sdk/timestamp.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22

33
import re
44
import warnings
5-
from datetime import UTC, datetime
5+
from datetime import datetime, timezone
66

77
from whenever import Date, Instant, Time, ZonedDateTime
88

9+
UTC = timezone.utc # Required for older versions of Python
10+
911
REGEX_MAPPING = {
1012
"seconds": r"(\d+)(s|sec|second|seconds)",
1113
"minutes": r"(\d+)(m|min|minute|minutes)",
@@ -76,19 +78,17 @@ def __repr__(self) -> str:
7678
def to_string(self, with_z: bool = True) -> str:
7779
if with_z:
7880
return self._obj.instant().format_common_iso()
79-
# iso8601_string = self._obj.format_common_iso()
80-
81-
# self.to_datetime().isoformat()
82-
# if iso8601_string[-1] == "Z":
83-
# iso8601_string = iso8601_string[:-1] + "+00:00"
8481
return self.to_datetime().isoformat()
8582

8683
def to_timestamp(self) -> int:
8784
return self._obj.timestamp()
8885

8986
def to_datetime(self) -> datetime:
9087
time_str = self.to_string()
91-
return datetime.strptime(time_str[:-1], "%Y-%m-%dT%H:%M:%S.%f").replace(tzinfo=UTC)
88+
try:
89+
return datetime.strptime(time_str[:-1], "%Y-%m-%dT%H:%M:%S.%f").replace(tzinfo=UTC)
90+
except ValueError:
91+
raise ValueError(f"Unable to convert {time_str} to datetime")
9292

9393
def __eq__(self, other: object) -> bool:
9494
if not isinstance(other, Timestamp):

tests/unit/sdk/test_timestamp.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
from datetime import UTC, datetime
1+
from datetime import datetime, timezone
22

33
import pytest
44
from whenever import Instant
55

66
from infrahub_sdk.timestamp import Timestamp, TimestampFormatError
77

8+
UTC = timezone.utc # Required for older versions of Python
9+
810

911
def test_init_empty():
1012
t1 = Timestamp()
@@ -47,6 +49,11 @@ def test_parse_string():
4749
pytest.param(
4850
"2023-12-31T23:59:59.999999Z", datetime(2023, 12, 31, 23, 59, 59, 999999, tzinfo=UTC), id="microseconds"
4951
),
52+
pytest.param(
53+
"2025-02-25T05:58:54.524191Z",
54+
datetime(2025, 2, 25, 5, 58, 54, 524191, tzinfo=UTC),
55+
id="milliseconds_with_offset",
56+
),
5057
],
5158
)
5259
def test_to_datetime(input_str, expected_datetime):

0 commit comments

Comments
 (0)