MCPcopy
hub / github.com/pydantic/pydantic / parse_datetime

Function parse_datetime

pydantic/v1/datetime_parse.py:175–210  ·  view source on GitHub ↗

Parse a datetime/int/float/string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raise ValueError if the input is well formatted but not a valid datetime. Raise Val

(value: Union[datetime, StrBytesIntFloat])

Source from the content-addressed store, hash-verified

173
174
175def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime:
176 """
177 Parse a datetime/int/float/string and return a datetime.datetime.
178
179 This function supports time zone offsets. When the input contains one,
180 the output uses a timezone with a fixed offset from UTC.
181
182 Raise ValueError if the input is well formatted but not a valid datetime.
183 Raise ValueError if the input isn't well formatted.
184 """
185 if isinstance(value, datetime):
186 return value
187
188 number = get_numeric(value, 'datetime')
189 if number is not None:
190 return from_unix_seconds(number)
191
192 if isinstance(value, bytes):
193 value = value.decode()
194
195 match = datetime_re.match(value) # type: ignore
196 if match is None:
197 raise errors.DateTimeError()
198
199 kw = match.groupdict()
200 if kw['microsecond']:
201 kw['microsecond'] = kw['microsecond'].ljust(6, '0')
202
203 tzinfo = _parse_timezone(kw.pop('tzinfo'), errors.DateTimeError)
204 kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None}
205 kw_['tzinfo'] = tzinfo
206
207 try:
208 return datetime(**kw_) # type: ignore
209 except ValueError:
210 raise errors.DateTimeError()
211
212
213def parse_duration(value: StrBytesIntFloat) -> timedelta:

Callers

nothing calls this directly

Calls 5

get_numericFunction · 0.85
from_unix_secondsFunction · 0.85
_parse_timezoneFunction · 0.85
decodeMethod · 0.45
itemsMethod · 0.45

Tested by

no test coverage detected