Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialization -> de-serialisation fails for small timedelta (< 100 microseconds) #3315

Closed
3 tasks done
fabien-brulport opened this issue Oct 12, 2021 · 0 comments · Fixed by #4329
Closed
3 tasks done
Labels
bug V1 Bug related to Pydantic V1.X

Comments

@fabien-brulport
Copy link

fabien-brulport commented Oct 12, 2021

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']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug V1 Bug related to Pydantic V1.X
Projects
None yet
1 participant