Skip to content

Commit ac2d548

Browse files
committed
Fix sketchy datetime.time approach
1 parent 57b0b4d commit ac2d548

File tree

2 files changed

+16
-23
lines changed

2 files changed

+16
-23
lines changed

aredis_om/model/encoders.py

+9-16
Original file line numberDiff line numberDiff line change
@@ -38,31 +38,24 @@
3838
from pydantic.json import ENCODERS_BY_TYPE
3939

4040

41+
# TODO: check if correct
4142
def date_to_timestamp(t: datetime.date) -> int:
4243
return calendar.timegm(t.timetuple())
4344

4445

46+
# TODO: check if correct
4547
def datetime_to_timestamp(t: datetime.datetime) -> int:
4648
return math.floor(t.astimezone(datetime.timezone.utc).timestamp() * 1000)
4749

4850

49-
# TODO: Find better / more correct approach!!!!!!!!!!!
51+
zero_time = datetime.datetime.fromtimestamp(0)
52+
zero_day = zero_time.date()
53+
54+
55+
# TODO: check if correct
5056
def time_to_timestamp(t: datetime.time) -> int:
51-
# TODO: Find better / more correct approach!!!!!!!!!!!
52-
offset = t.utcoffset()
53-
offset_ms = (
54-
math.floor(offset.total_seconds() * 1000) + offset.microseconds // 1000
55-
if offset is not None
56-
else 0
57-
)
58-
return (
59-
t.hour * 3600 * 1000
60-
+ t.minute * 60 * 1000
61-
+ t.second * 1000
62-
+ t.microsecond // 1000
63-
# TODO: Find better / more correct approach!!!!!!!!!!!
64-
- offset_ms
65-
)
57+
time_point = datetime.datetime.combine(zero_day, t, t.tzinfo)
58+
return datetime_to_timestamp(time_point)
6659

6760

6861
SetIntStr = Set[Union[int, str]]

tests/test_time.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,6 @@ class Meta:
149149
class PostTime(BaseModel):
150150
created: datetime.time = Field(index=True)
151151

152-
# TODO: Find better / more correct approach!!!!!!!!!!
153152
# TODO: Provide our field type instead of date datetime.time?
154153
# https://pydantic-docs.helpmanual.io/usage/types/#datetime-types
155154
# datetime.time is parsing only from time obj or iso? str
@@ -158,12 +157,13 @@ def time_validator(cls, value):
158157
if isinstance(value, str):
159158
value = int(value)
160159
if isinstance(value, int):
161-
return datetime.time(
162-
hour=value // 1000 // 3600 % 24,
163-
minute=value // 1000 // 60 % 60,
164-
second=value // 1000 % 60,
165-
microsecond=(value % 1000) * 1000,
166-
tzinfo=datetime.timezone.utc,
160+
# TODO: check if correct
161+
return (
162+
datetime.datetime.fromtimestamp(
163+
value // 1000, tz=datetime.timezone.utc
164+
)
165+
.time()
166+
.replace(tzinfo=datetime.timezone.utc)
167167
)
168168
return value
169169

0 commit comments

Comments
 (0)