@@ -35,24 +35,25 @@ class MyDatetimeValidator:
3535
3636 def tz_constraint_validator (
3737 self ,
38- value : dt.datetime ,
38+ value : Any ,
3939 handler : ValidatorFunctionWrapHandler, # (1)!
4040 ):
4141 """ Validate tz_constraint and tz_info."""
42+ result = handler(value) # (2)!
43+
4244 # handle naive datetimes
4345 if self .tz_constraint is None :
4446 assert (
45- value .tzinfo is None
47+ result .tzinfo is None
4648 ), ' tz_constraint is None, but provided value is tz-aware.'
47- return handler(value)
49+ return result
4850
4951 # validate tz_constraint and tz-aware tzinfo
5052 if self .tz_constraint not in pytz.all_timezones:
5153 raise PydanticUserError(
5254 f ' Invalid tz_constraint: { self .tz_constraint} ' ,
5355 code = ' unevaluable-type-annotation' ,
5456 )
55- result = handler(value) # (2)!
5657 assert self .tz_constraint == str (
5758 result.tzinfo
5859 ), f ' Invalid tzinfo: { str (result.tzinfo)} , expected: { self .tz_constraint} '
@@ -77,6 +78,10 @@ print(
7778)
7879# > 2023-01-01 00:00:00-07:53
7980
81+ naive_ta = TypeAdapter(Annotated[dt.datetime, MyDatetimeValidator()])
82+ print (naive_ta.validate_python(' 2023-01-01T00:00:00' ))
83+ # > 2023-01-01 00:00:00
84+
8085LONDON = ' Europe/London'
8186try :
8287 ta.validate_python(
@@ -122,15 +127,15 @@ class MyDatetimeValidator:
122127 upper_bound: int
123128
124129 def validate_tz_bounds (
125- self , value : dt.datetime , handler : ValidatorFunctionWrapHandler
130+ self , value : Any , handler : ValidatorFunctionWrapHandler
126131 ):
127132 """ Validate and test bounds"""
128- assert value.utcoffset() is not None , ' UTC offset must exist'
129133 assert self .lower_bound <= self .upper_bound, ' Invalid bounds'
130134
131135 result = handler(value)
136+ assert result.utcoffset() is not None , ' UTC offset must exist'
132137
133- hours_offset = value .utcoffset().total_seconds() / 3600
138+ hours_offset = result .utcoffset().total_seconds() / 3600
134139 assert (
135140 self .lower_bound <= hours_offset <= self .upper_bound
136141 ), ' Value out of bounds'
@@ -155,6 +160,9 @@ print(
155160)
156161# > 2023-01-01 00:00:00-07:53
157162
163+ print (ta.validate_json(' "2023-01-01T00:00:00-08:00"' ))
164+ # > 2023-01-01 00:00:00-08:00
165+
158166LONDON = ' Europe/London'
159167try :
160168 print (
0 commit comments