Skip to content

Commit 6e48e98

Browse files
committed
feat(constants): add from_milliseconds class method to DAVTime
1 parent 55251dc commit 6e48e98

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

asgi_webdav/constants.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,10 @@ def __init__(self, timestamp: float | None = None):
355355
self.timestamp = timestamp
356356
self.data = datetime.fromtimestamp(timestamp, tz=timezone.utc)
357357

358+
@classmethod
359+
def from_milliseconds(cls, timestamp: float) -> DAVTime:
360+
return cls(timestamp / 1_000)
361+
358362
@classmethod
359363
def from_microseconds(cls, timestamp: float) -> DAVTime:
360364
return cls(timestamp / 1_000_000)

tests/test_constants.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,40 @@ def test_DAVTime():
129129
assert dt.display(timezone_shanghai) == "1970-01-01 08:00:00+08:00"
130130

131131

132+
def test_DAVTime_from_milliseconds():
133+
"""测试从毫秒时间戳创建 DAVTime 实例"""
134+
# 测试 0 毫秒,对应 Unix 纪元
135+
dt = DAVTime.from_milliseconds(0.0)
136+
assert isinstance(dt, DAVTime)
137+
assert dt.timestamp == 0.0
138+
assert dt.iso_8601 == "1970-01-01T00:00:00+00:00"
139+
140+
# 测试 1 秒(1,000 毫秒)
141+
dt = DAVTime.from_milliseconds(1000.0)
142+
assert dt.timestamp == 1.0
143+
assert dt.iso_8601 == "1970-01-01T00:00:01+00:00"
144+
145+
# 测试负毫秒值(1970 年之前的时间)
146+
dt = DAVTime.from_milliseconds(-1000.0)
147+
assert dt.timestamp == -1.0
148+
assert dt.iso_8601 == "1969-12-31T23:59:59+00:00"
149+
150+
# 测试浮点数毫秒值(带小数部分)
151+
dt = DAVTime.from_milliseconds(1500.5)
152+
assert dt.timestamp == 1.5005 # 1.5 秒 + 0.5 毫秒
153+
154+
# 验证通过 from_milliseconds 创建的实例与直接使用秒级时间戳创建的实例行为一致
155+
milliseconds = 2123.456
156+
dt_from_milli = DAVTime.from_milliseconds(milliseconds)
157+
dt_from_seconds = DAVTime(milliseconds / 1000)
158+
assert dt_from_milli.timestamp == dt_from_seconds.timestamp
159+
assert dt_from_milli.iso_8601 == dt_from_seconds.iso_8601
160+
161+
# 可选:验证其他格式化属性,如 http_date, w3c 等
162+
assert dt_from_milli.http_date == dt_from_seconds.http_date
163+
assert dt_from_milli.w3c == dt_from_seconds.w3c
164+
165+
132166
def test_DAVTime_from_microseconds():
133167
"""测试从微秒时间戳创建 DAVTime 实例"""
134168
# 测试 0 微秒,对应 Unix 纪元

0 commit comments

Comments
 (0)