-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Description
Checks
- I added a descriptive title to this issue
- I have searched (google, github) for similar issues and couldn't find anything
- I have read and followed the docs and still think this is a bug
Bug
The serialization -> de-serialization of a model with small timedelta raises a ValidationError. The de-serialization fails only when the timedelta is below 100 microseconds, see the following example:
from datetime import timedelta
from pydantic import BaseModel
class Model(BaseModel):
duration: timedelta
# This works
model = Model(duration=timedelta(microseconds=100))
Model.parse_raw(model.json())
# This Fails
model = Model(duration=timedelta(microseconds=99))
Model.parse_raw(model.json())Last line throws the following error:
pydantic.error_wrappers.ValidationError: 1 validation error for Model
duration
invalid duration format (type=value_error.duration)I believe the error comes from the parse_duration function, and in particular the line where the input value is converted to str.
https://github.com/samuelcolvin/pydantic/blob/c256dccbb383a7fd462f62fcb5d55558eb3cb108/pydantic/datetime_parse.py#L226-L231
Indeed str(0.0001) gives "0.0001" but str(0.000099) gives "9.9e-5", thus the re.match fails.
Changing value = str(value) to value = "f{value:.6f}" should fix this. I would be happy to create a PR to solve the issue.
System information
Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":
pydantic version: 1.8.2
pydantic compiled: True
install path: <my-home>/.pyenv/versions/3.7.11/envs/pydantic/lib/python3.7/site-packages/pydantic
python version: 3.7.11 (default, Aug 31 2021, 20:43:02) [Clang 10.0.1 (clang-1001.0.46.4)]
platform: Darwin-19.6.0-x86_64-i386-64bit
optional deps. installed: ['typing-extensions']