Skip to content

Commit

Permalink
Add support for timestamp conversion with sub-second precision
Browse files Browse the repository at this point in the history
  • Loading branch information
thombashi committed May 10, 2019
1 parent 08e7003 commit a195859
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 11 deletions.
14 changes: 12 additions & 2 deletions test/checker/test_checker_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,18 @@ class Test_DateTime_is_type(object):
[False],
)
)
+ list(itertools.product(["2017-03-22T10:00:00+0900"], [StrictLevel.MIN], [True]))
+ list(itertools.product(["2017-03-22T10:00:00+0900"], [StrictLevel.MAX], [False])),
+ list(
itertools.product(
["2017-03-22T10:00:00+0900", 1485685623, "1485685623", "1524930937.003555"],
[StrictLevel.MIN],
[True],
)
)
+ list(
itertools.product(
["2017-03-22T10:00:00+0900", 1485685623, "1485685623"], [StrictLevel.MAX], [False]
)
),
)
def test_normal(self, value, strict_level, expected):
type_object = class_under_test(value, strict_level)
Expand Down
33 changes: 24 additions & 9 deletions typepy/converter/_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,19 +67,34 @@ def __from_datetime(self):

def __from_timestamp(self):
from ..type._integer import Integer
from ..type._realnumber import RealNumber

conv_error = TypeConversionError(
"timestamp is out of the range of values supported by the platform"
)

timestamp = Integer(self._value, strict_level=1).try_convert()
if timestamp is None:
return None
if timestamp:
try:
self.__datetime = datetime.fromtimestamp(timestamp, self.__timezone)
except (ValueError, OSError, OverflowError):
raise conv_error

try:
self.__datetime = datetime.fromtimestamp(timestamp, self.__timezone)
except (ValueError, OSError, OverflowError):
raise TypeConversionError(
"timestamp is out of the range of values supported by the platform"
)
return self.__datetime

return self.__datetime
timestamp = RealNumber(self._value, strict_level=1).try_convert()
if timestamp:
us = (timestamp - int(timestamp)) * 1000000
try:
self.__datetime = datetime.fromtimestamp(timestamp, self.__timezone).replace(
microsecond=us
)
except (ValueError, OSError, OverflowError):
raise conv_error

return self.__datetime

return None

def __from_datetime_string(self):
import dateutil.parser
Expand Down

0 comments on commit a195859

Please sign in to comment.