Page Menu
Home
Software Heritage
Search
Configure Global Search
Log In
Files
F7124848
D5861.id21012.diff
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
1 KB
Subscribers
None
D5861.id21012.diff
View Options
diff --git a/swh/model/model.py b/swh/model/model.py
--- a/swh/model/model.py
+++ b/swh/model/model.py
@@ -257,6 +257,21 @@
def from_datetime(cls, dt: datetime.datetime):
return cls.from_dict(dt)
+ def to_datetime(self) -> datetime.datetime:
+ """Convert to a datetime (with a timezone set to the recorded fixed UTC offset)
+
+ Beware that this conversion can be lossy: the negative_utc flag is not
+ taken into consideration (since it cannot be represented in a
+ datetime). Also note that it may fail due to type overflow.
+
+ """
+ timestamp = datetime.datetime.fromtimestamp(
+ self.timestamp.seconds,
+ datetime.timezone(datetime.timedelta(minutes=self.offset)),
+ )
+ timestamp = timestamp.replace(microsecond=self.timestamp.microseconds)
+ return timestamp
+
@classmethod
def from_iso8601(cls, s):
"""Builds a TimestampWithTimezone from an ISO8601-formatted string.
diff --git a/swh/model/tests/test_model.py b/swh/model/tests/test_model.py
--- a/swh/model/tests/test_model.py
+++ b/swh/model/tests/test_model.py
@@ -48,6 +48,8 @@
)
from swh.model.tests.swh_model_data import TEST_OBJECTS
from swh.model.tests.test_identifiers import (
+ TS_DATETIMES,
+ TS_TIMEZONES,
content_example,
directory_example,
metadata_example,
@@ -329,6 +331,17 @@
)
+@pytest.mark.parametrize("date", TS_DATETIMES)
+@pytest.mark.parametrize("tz", TS_TIMEZONES)
+@pytest.mark.parametrize("microsecond", [0, 1, 10, 100, 1000, 999999])
+def test_timestampwithtimezone_to_datetime(date, tz, microsecond):
+ date = date.replace(tzinfo=tz, microsecond=microsecond)
+ tstz = TimestampWithTimezone.from_datetime(date)
+
+ assert tstz.to_datetime() == date
+ assert tstz.to_datetime().utcoffset() == date.utcoffset()
+
+
def test_person_from_fullname():
"""The author should have name, email and fullname filled.
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Dec 21 2024, 9:48 PM (11 w, 4 d ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3220634
Attached To
D5861: Add a TimestampWithTimezone.to_datetime() method
Event Timeline
Log In to Comment