Repository: pydantic/pydantic

Issue:
time ignores timedelta without error
# Bug

Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
pydantic version: 1.5.1
pydantic compiled: True
install path: C:\...\.venv37\Lib\site-packages\pydantic
python version: 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)]
platform: Windows-10-10.0.17134-SP0
optional deps. installed: ['typing-extensions']
```

In the documentation at https://pydantic-docs.helpmanual.io/usage/types/#datetime-types it is stated that

> - time fields can be:
>    - time, existing time object
>    - str, following formats work:
>        - HH:MM[:SS[.ffffff]]

but as shown in the example below strings like `11:05+05:00`
- are accepted and raise no error
- loose the timedelta information

Loosing information (especially timedelta) without recognition can e.g. lead to discrepancies when collecting data from different sources and a relationship between single pieces of data must be established based on a timestamp.

I tried to track it down to the root cause:
```py
>>> from pydantic import datetime_parse

>>> incorrect_time = datetime_parse.parse_time("11:05+05:00")
>>> print(incorrect_time)
datetime.time(11, 5)
# Here I would expect to 
# - either get an error because it is not stated that a format having a timedelta is accepted
# - or a datetime.time(11, 5, tzinfo=datetime.timezone(datetime.timedelta(seconds=18000)) as datetime.time.fromisoformat would return
```



Comments:
This sounds like a bug, but it might need to wait for v2 to be fixed since it could be considered a breaking change. 
I have a fix for this, duplicating the datetime's method of handling timedeltas. The rest of the module doesn't seem refactored to reduce duplicated code. I assume this change is is okay / better by keeping it that way?

This is my work so far: https://github.com/samuelcolvin/pydantic/commit/1d59058a2ae6f4b0f2f119b8eddc1529c5789d86

Patch:
diff --git a/pydantic/datetime_parse.py b/pydantic/datetime_parse.py
--- a/pydantic/datetime_parse.py
+++ b/pydantic/datetime_parse.py
@@ -16,23 +16,21 @@
 """
 import re
 from datetime import date, datetime, time, timedelta, timezone
-from typing import Dict, Union
+from typing import Dict, Optional, Type, Union
 
 from . import errors
 
-date_re = re.compile(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$')
-
-time_re = re.compile(
-    r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
-)
-
-datetime_re = re.compile(
-    r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
-    r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
+date_expr = r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
+time_expr = (
+    r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
     r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
     r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$'
 )
 
+date_re = re.compile(f'{date_expr}$')
+time_re = re.compile(time_expr)
+datetime_re = re.compile(f'{date_expr}[T ]{time_expr}')
+
 standard_duration_re = re.compile(
     r'^'
     r'(?:(?P<days>-?\d+) (days?, )?)?'
@@ -81,6 +79,22 @@ def from_unix_seconds(seconds: Union[int, float]) -> datetime:
     return dt.replace(tzinfo=timezone.utc)
 
 
+def _parse_timezone(value: Optional[str], error: Type[Exception]) -> Union[None, int, timezone]:
+    if value == 'Z':
+        return timezone.utc
+    elif value is not None:
+        offset_mins = int(value[-2:]) if len(value) > 3 else 0
+        offset = 60 * int(value[1:3]) + offset_mins
+        if value[0] == '-':
+            offset = -offset
+        try:
+            return timezone(timedelta(minutes=offset))
+        except ValueError:
+            raise error()
+    else:
+        return None
+
+
 def parse_date(value: Union[date, StrBytesIntFloat]) -> date:
     """
     Parse a date/int/float/string and return a datetime.date.
@@ -117,8 +131,6 @@ def parse_time(value: Union[time, StrBytesIntFloat]) -> time:
     """
     Parse a time/string and return a datetime.time.
 
-    This function doesn't support time zone offsets.
-
     Raise ValueError if the input is well formatted but not a valid time.
     Raise ValueError if the input isn't well formatted, in particular if it contains an offset.
     """
@@ -143,7 +155,9 @@ def parse_time(value: Union[time, StrBytesIntFloat]) -> time:
     if kw['microsecond']:
         kw['microsecond'] = kw['microsecond'].ljust(6, '0')
 
-    kw_ = {k: int(v) for k, v in kw.items() if v is not None}
+    tzinfo = _parse_timezone(kw.pop('tzinfo'), errors.TimeError)
+    kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None}
+    kw_['tzinfo'] = tzinfo
 
     try:
         return time(**kw_)  # type: ignore
@@ -179,19 +193,8 @@ def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime:
     if kw['microsecond']:
         kw['microsecond'] = kw['microsecond'].ljust(6, '0')
 
-    tzinfo_str = kw.pop('tzinfo')
-    if tzinfo_str == 'Z':
-        tzinfo = timezone.utc
-    elif tzinfo_str is not None:
-        offset_mins = int(tzinfo_str[-2:]) if len(tzinfo_str) > 3 else 0
-        offset = 60 * int(tzinfo_str[1:3]) + offset_mins
-        if tzinfo_str[0] == '-':
-            offset = -offset
-        tzinfo = timezone(timedelta(minutes=offset))
-    else:
-        tzinfo = None
-
-    kw_: Dict[str, Union[int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None}
+    tzinfo = _parse_timezone(kw.pop('tzinfo'), errors.DateTimeError)
+    kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None}
     kw_['tzinfo'] = tzinfo
 
     try:


Test patch:
diff --git a/tests/test_datetime_parse.py b/tests/test_datetime_parse.py
--- a/tests/test_datetime_parse.py
+++ b/tests/test_datetime_parse.py
@@ -65,12 +65,20 @@ def test_date_parsing(value, result):
         (3610, time(1, 0, 10)),
         (3600.5, time(1, 0, 0, 500000)),
         (86400 - 1, time(23, 59, 59)),
+        ('11:05:00-05:30', time(11, 5, 0, tzinfo=create_tz(-330))),
+        ('11:05:00-0530', time(11, 5, 0, tzinfo=create_tz(-330))),
+        ('11:05:00Z', time(11, 5, 0, tzinfo=timezone.utc)),
+        ('11:05:00+00', time(11, 5, 0, tzinfo=timezone.utc)),
+        ('11:05-06', time(11, 5, 0, tzinfo=create_tz(-360))),
+        ('11:05+06', time(11, 5, 0, tzinfo=create_tz(360))),
         # Invalid inputs
         (86400, errors.TimeError),
         ('xxx', errors.TimeError),
         ('091500', errors.TimeError),
         (b'091500', errors.TimeError),
         ('09:15:90', errors.TimeError),
+        ('11:05:00Y', errors.TimeError),
+        ('11:05:00-25:00', errors.TimeError),
     ],
 )
 def test_time_parsing(value, result):
@@ -108,6 +116,7 @@ def test_time_parsing(value, result):
         # Invalid inputs
         ('x20120423091500', errors.DateTimeError),
         ('2012-04-56T09:15:90', errors.DateTimeError),
+        ('2012-04-23T11:05:00-25:00', errors.DateTimeError),
         (19_999_999_999, datetime(2603, 10, 11, 11, 33, 19, tzinfo=timezone.utc)),  # just before watershed
         (20_000_000_001, datetime(1970, 8, 20, 11, 33, 20, 1000, tzinfo=timezone.utc)),  # just after watershed
         (1_549_316_052, datetime(2019, 2, 4, 21, 34, 12, 0, tzinfo=timezone.utc)),  # nowish in s