"""Types for narrowing on the builtin datetime types.These types can be used without installing any extra dependencies, however, to parsestrings, python-dateutil must be installed or a:py:class:`phantom.errors.MissingDependency` error will be raised when calling parse.You can install python-dateutil by using the ``[dateutil]`` or ``[all]`` extras."""from__future__importannotationsimportdatetimefrom.importPhantomfrom.import_hypothesisfrom.boundsimportparse_strfrom.errorsimportMissingDependencyfrom.predicates.datetimeimportis_tz_awarefrom.predicates.datetimeimportis_tz_naivefrom.schemaimportSchematry:importdateutil.parserparse_datetime_str=dateutil.parser.parseDateutilParseError=dateutil.parser.ParserErrorexceptImportErrorase:exception=edefparse_datetime_str(*_:object,**__:object,)->datetime.datetime:raiseMissingDependency("python-dateutil needs to be installed to use this type for parsing. It ""can be installed with the phantom-types[dateutil] extra.")fromexceptionclassDateutilParseError(Exception):# type: ignore[no-redef]...__all__=("TZAware","TZNaive")defparse_datetime(value:object)->datetime.datetime:ifisinstance(value,datetime.datetime):returnvaluestr_value=parse_str(value)try:returnparse_datetime_str(str_value)exceptDateutilParseErrorasexc:raiseTypeError("Could not parse datetime from given string")fromexc
[docs]classTZAware(datetime.datetime,Phantom,predicate=is_tz_aware):""" A type for helping ensure that ``datetime`` objects are always timezone aware. >>> isinstance(datetime.datetime.now(), TZAware) False >>> isinstance(datetime.datetime.now(tz=datetime.timezone.utc), TZAware) True """# A property of being aware is (dt.tzinfo != None), so we can safely narrow this# attribute to not include None.tzinfo:datetime.tzinfo
@classmethoddef__schema__(cls)->Schema:return{**super().__schema__(),"description":"A date-time with timezone data.",}@classmethoddef__register_strategy__(cls)->_hypothesis.SearchStrategy:fromhypothesis.strategiesimportdatetimesfromhypothesis.strategiesimporttimezonesreturndatetimes(timezones=timezones())
@classmethoddef__schema__(cls)->Schema:return{**super().__schema__(),"description":"A date-time without timezone data.","format":"date-time-naive",}@classmethoddef__register_strategy__(cls)->_hypothesis.SearchStrategy:fromhypothesis.strategiesimportdatetimesfromhypothesis.strategiesimportnonereturndatetimes(timezones=none())