Skip to content

Commit

Permalink
feat(timedelta): add scientific notation
Browse files Browse the repository at this point in the history
  • Loading branch information
JeanArhancet committed Oct 22, 2021
1 parent c256dcc commit 34ff7d5
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
1 change: 1 addition & 0 deletions changes/3315-JeanArhancet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add scientific notation in timedelta
4 changes: 4 additions & 0 deletions pydantic/datetime_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
r'(?:\.(?P<microseconds>\d{1,6})\d{0,6})?'
r'$'
)
# Support scientific notation for duration
scientific_notation_duration_re = re.compile(r'^([+\-]?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+))?$')

# Support the sections of ISO 8601 date representation that are accepted by timedelta
iso8601_duration_re = re.compile(
Expand Down Expand Up @@ -228,6 +230,8 @@ def parse_duration(value: StrBytesIntFloat) -> timedelta:
value = value.decode()

try:
if scientific_notation_duration_re.match(value):
value = f"{float(value):.6f}"
match = standard_duration_re.match(value) or iso8601_duration_re.match(value)
except TypeError:
raise TypeError('invalid type; expected timedelta, string, bytes, int or float')
Expand Down
10 changes: 10 additions & 0 deletions tests/test_datetime_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ def test_datetime_parsing(value, result):
timedelta(days=-4, minutes=15, seconds=30), # negative durations
timedelta(minutes=15, seconds=30), # minute & seconds
timedelta(seconds=30), # seconds
timedelta(microseconds=99) # microseconds
],
)
def test_parse_python_format(delta):
Expand Down Expand Up @@ -210,6 +211,15 @@ def test_parse_python_format(delta):
('PT5S', timedelta(seconds=5)),
('PT0.000005S', timedelta(microseconds=5)),
(b'PT0.000005S', timedelta(microseconds=5)),
# Scientific Notation
('+0003', errors.DurationError),
(9.9e-05, timedelta(microseconds=99)),
('9.9e-05', timedelta(microseconds=99)),
(9.9e05, timedelta(days=11, seconds=39600)),
(+3, timedelta(seconds=3)),
(-4.70e+9, timedelta(days=-54399, seconds=73600)),
(-.2E-4, timedelta(days=-1, seconds=86399, microseconds=999980)),
(-7.6603, timedelta(days=-1, seconds=86392, microseconds=339700))
],
)
def test_parse_durations(value, result):
Expand Down

0 comments on commit 34ff7d5

Please sign in to comment.