Temporal Types
Temporal types in this codebase provide robust validation and parsing for dates, times, datetimes, and durations (timedeltas). These types are designed to handle ISO 8601 formatted strings, bytes, and numeric inputs while enforcing strict constraints on ranges and timezone awareness.
Core Temporal Schemas
The validation logic is defined through four primary schema classes in pydantic_core.core_schema:
DateSchema: Validatesdatetime.dateobjects.DatetimeSchema: Validatesdatetime.datetimeobjects, including timezone handling.TimeSchema: Validatesdatetime.timeobjects.TimedeltaSchema: Validatesdatetime.timedeltaobjects, representing durations.
Parsing Logic
Each schema supports multiple input formats:
- Native Objects: Direct instances of
date,datetime,time, ortimedelta. - Strings and Bytes: ISO 8601 formatted strings (e.g.,
'2023-12-25','12:30:00','2023-12-25T12:30:00Z'). - Numeric Values:
- For
TimeSchema, integers or floats are treated as seconds since midnight. - For
TimedeltaSchema, they are treated as total seconds. - For
DatetimeSchema, they are treated as Unix timestamps.
- For
from datetime import datetime
from pydantic_core import SchemaValidator, core_schema
# DatetimeSchema parsing an ISO 8601 string
schema = core_schema.datetime_schema()
v = SchemaValidator(schema)
assert v.validate_python('2023-12-25T12:00:00Z') == datetime(2023, 12, 25, 12, 0, tzinfo=None) # Simplified for example
Range Constraints
All temporal schemas support standard comparison constraints: le (less than or equal), ge (greater than or equal), lt (less than), and gt (greater than).
from datetime import date
from pydantic_core import SchemaValidator, core_schema
# DateSchema with range constraints
schema = core_schema.date_schema(le=date(2020, 1, 1), ge=date(2019, 1, 1))
v = SchemaValidator(schema)
assert v.validate_python(date(2019, 6, 1)) == date(2019, 6, 1)
Relative Validation with now_op
DateSchema and DatetimeSchema include a now_op field that allows validation relative to the current moment. This is useful for enforcing that a date is in the past or future.
now_op: Set to'past'or'future'.now_utc_offset: An optional integer representing the UTC offset in seconds (defaults to the local system offset).
from datetime import date, timedelta
from pydantic_core import SchemaValidator, core_schema
# Validates that the date is in the past
v = SchemaValidator(core_schema.date_schema(now_op='past'))
v.validate_python(date.today() - timedelta(days=1))
Timezone and Precision Control
Timezone Constraints
DatetimeSchema and TimeSchema use tz_constraint to enforce whether a value must be timezone-aware or naive:
'aware': Must have timezone information.'naive': Must not have timezone information.int: An integer representing a specific required fixed offset in seconds.
Microsecond Precision
When parsing strings with high-precision sub-second data, microseconds_precision determines the behavior:
'truncate': (Default) Truncates extra digits beyond 6 (microseconds).'error': Raises aValidationErrorif the precision exceeds microseconds.
# Error on sub-microsecond precision
v = SchemaValidator(core_schema.time_schema(microseconds_precision='error'))
# This would fail if the input had more than 6 decimal places for seconds
Duration Validation (TimedeltaSchema)
The TimedeltaSchema handles complex ISO 8601 duration strings, such as P1DT2H (1 day, 2 hours).
from datetime import timedelta
from pydantic_core import SchemaValidator, core_schema
v = SchemaValidator(core_schema.timedelta_schema())
# Parsing complex ISO 8601 duration
assert v.validate_python('P0Y0M3D2WT1H2M3.5S') == timedelta(
days=3, weeks=2, hours=1, minutes=2, seconds=3, milliseconds=500
)
Serialization Configuration
Temporal types are serialized to JSON as ISO 8601 strings by default. This behavior can be adjusted via CoreConfig using ser_json_temporal.
ser_json_temporal: Options include'iso8601','seconds', or'milliseconds'.ser_json_timedelta: Specific to durations, allowing'iso8601'or'float'(total seconds).
If ser_json_temporal is set, it typically takes precedence over type-specific serialization settings for temporal values.