Skip to content

# datatype

## `xsdata.models.datatype`

### `DateFormat`

Xml date formats.

Source code in `xsdata/models/datatype.py`

    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44

    class DateFormat:
        """Xml date formats."""

        DATE = "%Y-%m-%d%z"
        TIME = "%H:%M:%S%z"
        DATE_TIME = "%Y-%m-%dT%H:%M:%S%z"
        G_DAY = "---%d%z"
        G_MONTH = "--%m%z"
        G_MONTH_DAY = "--%m-%d%z"
        G_YEAR = "%Y%z"
        G_YEAR_MONTH = "%Y-%m%z"

### `XmlDate`

Bases: `NamedTuple`

Concrete xs:date builtin type.

Represents iso 8601 date format [-]CCYY-MM-DD[Z|(+|-)hh:mm] with rich comparisons and hashing.

Attributes:

Name | Type | Description
--- | --- | ---
`year` | `int` | Any signed integer, eg (0, -535, 2020)
`month` | `int` | Unsigned integer between 1-12
`day` | `int` | Unsigned integer between 1-31
`offset` | `int | None` | Signed integer representing timezone offset in minutes

Source code in `xsdata/models/datatype.py`

     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136

    class XmlDate(NamedTuple):
        """Concrete xs:date builtin type.

        Represents iso 8601 date format [-]CCYY-MM-DD[Z|(+|-)hh:mm] with
        rich comparisons and hashing.

        Attributes:
            year: Any signed integer, eg (0, -535, 2020)
            month: Unsigned integer between 1-12
            day: Unsigned integer between 1-31
            offset: Signed integer representing timezone offset in minutes
        """

        year: int
        month: int
        day: int
        offset: int | None = None

        def replace(
            self,
            year: int | None = None,
            month: int | None = None,
            day: int | None = None,
            offset: int | None = True,
        ) -> "XmlDate":
            """Return a new instance replacing the specified fields with new values."""
            if year is None:
                year = self.year
            if month is None:
                month = self.month
            if day is None:
                day = self.day
            if offset is True:
                offset = self.offset

            return type(self)(year, month, day, offset)

        @classmethod
        def from_string(cls, string: str) -> "XmlDate":
            """Initialize from string with format `%Y-%m-%dT%z`."""
            year, month, day, offset = parse_date_args(string, DateFormat.DATE)
            assert year is not None
            assert month is not None
            assert day is not None
            return cls(year, month, day, offset)

        @classmethod
        def from_date(cls, obj: datetime.date) -> "XmlDate":
            """Initialize from a `datetime.date` instance."""
            return cls(obj.year, obj.month, obj.day)

        @classmethod
        def from_datetime(cls, obj: datetime.datetime) -> "XmlDate":
            """Initialize from `datetime.datetime` instance."""
            return cls(obj.year, obj.month, obj.day, calculate_offset(obj))

        @classmethod
        def today(cls) -> "XmlDate":
            """Initialize with the current date."""
            return cls.from_date(datetime.date.today())

        def to_date(self) -> datetime.date:
            """Convert to a :`datetime.date` instance."""
            return datetime.date(self.year, self.month, self.day)

        def to_datetime(self) -> datetime.datetime:
            """Convert to a `datetime.datetime` instance."""
            tz_info = calculate_timezone(self.offset)
            return datetime.datetime(self.year, self.month, self.day, tzinfo=tz_info)

        def __str__(self) -> str:
            """Return the date formatted according to ISO 8601 for xml.

            Examples:
                - 2001-10-26
                - 2001-10-26+02:00
                - 2001-10-26Z

            Returns:
                The str result.
            """
            return format_date(self.year, self.month, self.day) + format_offset(self.offset)

        def __repr__(self) -> str:
            """Return the instance string representation."""
            args = [self.year, self.month, self.day, self.offset]
            if args[-1] is None:
                del args[-1]

            return f"{self.__class__.__qualname__}({', '.join(map(str, args))})"

#### `replace(year=None, month=None, day=None, offset=True)`

Return a new instance replacing the specified fields with new values.

Source code in `xsdata/models/datatype.py`

    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82

    def replace(
        self,
        year: int | None = None,
        month: int | None = None,
        day: int | None = None,
        offset: int | None = True,
    ) -> "XmlDate":
        """Return a new instance replacing the specified fields with new values."""
        if year is None:
            year = self.year
        if month is None:
            month = self.month
        if day is None:
            day = self.day
        if offset is True:
            offset = self.offset

        return type(self)(year, month, day, offset)

#### `from_string(string)` `classmethod`

Initialize from string with format `%Y-%m-%dT%z`.

Source code in `xsdata/models/datatype.py`

    84
    85
    86
    87
    88
    89
    90
    91

    @classmethod
    def from_string(cls, string: str) -> "XmlDate":
        """Initialize from string with format `%Y-%m-%dT%z`."""
        year, month, day, offset = parse_date_args(string, DateFormat.DATE)
        assert year is not None
        assert month is not None
        assert day is not None
        return cls(year, month, day, offset)

#### `from_date(obj)` `classmethod`

Initialize from a `datetime.date` instance.

Source code in `xsdata/models/datatype.py`

    93
    94
    95
    96

    @classmethod
    def from_date(cls, obj: datetime.date) -> "XmlDate":
        """Initialize from a `datetime.date` instance."""
        return cls(obj.year, obj.month, obj.day)

#### `from_datetime(obj)` `classmethod`

Initialize from `datetime.datetime` instance.

Source code in `xsdata/models/datatype.py`

     98
     99
    100
    101

    @classmethod
    def from_datetime(cls, obj: datetime.datetime) -> "XmlDate":
        """Initialize from `datetime.datetime` instance."""
        return cls(obj.year, obj.month, obj.day, calculate_offset(obj))

#### `today()` `classmethod`

Initialize with the current date.

Source code in `xsdata/models/datatype.py`

    103
    104
    105
    106

    @classmethod
    def today(cls) -> "XmlDate":
        """Initialize with the current date."""
        return cls.from_date(datetime.date.today())

#### `to_date()`

Convert to a :`datetime.date` instance.

Source code in `xsdata/models/datatype.py`

    108
    109
    110

    def to_date(self) -> datetime.date:
        """Convert to a :`datetime.date` instance."""
        return datetime.date(self.year, self.month, self.day)

#### `to_datetime()`

Convert to a `datetime.datetime` instance.

Source code in `xsdata/models/datatype.py`

    112
    113
    114
    115

    def to_datetime(self) -> datetime.datetime:
        """Convert to a `datetime.datetime` instance."""
        tz_info = calculate_timezone(self.offset)
        return datetime.datetime(self.year, self.month, self.day, tzinfo=tz_info)

#### `__str__()`

Return the date formatted according to ISO 8601 for xml.

Examples:

- 2001-10-26
- 2001-10-26+02:00
- 2001-10-26Z

Returns:

Type | Description
--- | ---
`str` | The str result.

Source code in `xsdata/models/datatype.py`

    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128

    def __str__(self) -> str:
        """Return the date formatted according to ISO 8601 for xml.

        Examples:
            - 2001-10-26
            - 2001-10-26+02:00
            - 2001-10-26Z

        Returns:
            The str result.
        """
        return format_date(self.year, self.month, self.day) + format_offset(self.offset)

#### `__repr__()`

Return the instance string representation.

Source code in `xsdata/models/datatype.py`

    130
    131
    132
    133
    134
    135
    136

    def __repr__(self) -> str:
        """Return the instance string representation."""
        args = [self.year, self.month, self.day, self.offset]
        if args[-1] is None:
            del args[-1]

        return f"{self.__class__.__qualname__}({', '.join(map(str, args))})"

### `XmlDateTime`

Bases: `NamedTuple`

Concrete xs:dateTime builtin type.

Represents iso 8601 date time format `[-]CCYY-MM-DDThh:mm: ss[Z|(+|-)hh:mm]` with rich comparisons and hashing.

Attributes:

Name | Type | Description
--- | --- | ---
`year` | `int` | Any signed integer, eg (0, -535, 2020)
`month` | `int` | Unsigned integer between 1-12
`day` | `int` | Unsigned integer between 1-31
`hour` | `int` | Unsigned integer between 0-24
`minute` | `int` | Unsigned integer between 0-59
`second` | `int` | Unsigned integer between 0-59
`fractional_second` | `int` | Unsigned integer between 0-999999999
`offset` | `int | None` | Signed integer representing timezone offset in minutes

Source code in `xsdata/models/datatype.py`

    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337

    class XmlDateTime(NamedTuple):
        """Concrete xs:dateTime builtin type.

        Represents iso 8601 date time format `[-]CCYY-MM-DDThh:mm: ss[Z|(+|-)hh:mm]`
        with rich comparisons and hashing.

        Attributes:
            year: Any signed integer, eg (0, -535, 2020)
            month: Unsigned integer between 1-12
            day: Unsigned integer between 1-31
            hour: Unsigned integer between 0-24
            minute: Unsigned integer between 0-59
            second: Unsigned integer between 0-59
            fractional_second: Unsigned integer between 0-999999999
            offset: Signed integer representing timezone offset in minutes
        """

        year: int
        month: int
        day: int
        hour: int
        minute: int
        second: int
        fractional_second: int = 0
        offset: int | None = None

        @property
        def microsecond(self) -> int:
            """Calculate the instance microseconds."""
            return self.fractional_second // 1000

        @property
        def duration(self) -> float:
            """Calculate the instance signed duration in seconds."""
            if self.year < 0:
                negative = True
                year = -self.year
            else:
                negative = False
                year = self.year

            total = (
                year * DS_YEAR
                + self.month * DS_MONTH
                + self.day * DS_DAY
                + self.hour * DS_HOUR
                + self.minute * DS_MINUTE
                + self.second
                + self.fractional_second * DS_FRACTIONAL_SECOND
                + (self.offset or 0) * DS_OFFSET
            )
            return -total if negative else total

        @classmethod
        def from_string(cls, string: str) -> "XmlDateTime":
            """Initialize from string with format `%Y-%m-%dT%H:%M:%S%z`."""
            (
                year,
                month,
                day,
                hour,
                minute,
                second,
                fractional_second,
                offset,
            ) = parse_date_args(string, DateFormat.DATE_TIME)

            assert year is not None
            assert month is not None
            assert day is not None
            assert hour is not None
            assert minute is not None
            assert second is not None
            assert fractional_second is not None

            validate_date(year, month, day)
            validate_time(hour, minute, second, fractional_second)

            return cls(year, month, day, hour, minute, second, fractional_second, offset)

        @classmethod
        def from_datetime(cls, obj: datetime.datetime) -> "XmlDateTime":
            """Initialize from `datetime.datetime` instance."""
            return cls(
                obj.year,
                obj.month,
                obj.day,
                obj.hour,
                obj.minute,
                obj.second,
                obj.microsecond * 1000,
                calculate_offset(obj),
            )

        @classmethod
        def now(cls, tz: datetime.timezone | None = None) -> "XmlDateTime":
            """Initialize with the current datetime and the given timezone."""
            return cls.from_datetime(datetime.datetime.now(tz=tz))

        @classmethod
        def utcnow(cls) -> "XmlDateTime":
            """Initialize with the current datetime and utc timezone."""
            return cls.from_datetime(datetime.datetime.now(datetime.timezone.utc))

        def to_datetime(self) -> datetime.datetime:
            """Return a `datetime.datetime` instance."""
            return datetime.datetime(
                self.year,
                self.month,
                self.day,
                self.hour,
                self.minute,
                self.second,
                self.microsecond,
                tzinfo=calculate_timezone(self.offset),
            )

        def replace(
            self,
            year: int | None = None,
            month: int | None = None,
            day: int | None = None,
            hour: int | None = None,
            minute: int | None = None,
            second: int | None = None,
            fractional_second: int | None = None,
            offset: int | None = True,
        ) -> "XmlDateTime":
            """Return a new instance replacing the specified fields with new values."""
            if year is None:
                year = self.year
            if month is None:
                month = self.month
            if day is None:
                day = self.day
            if hour is None:
                hour = self.hour
            if minute is None:
                minute = self.minute
            if second is None:
                second = self.second
            if fractional_second is None:
                fractional_second = self.fractional_second
            if offset is True:
                offset = self.offset

            return type(self)(
                year, month, day, hour, minute, second, fractional_second, offset
            )

        def __str__(self) -> str:
            """Return the datetime formatted according to ISO 8601 for xml.

            Examples:
                - 2001-10-26T21:32:52
                - 2001-10-26T21:32:52+02:00
                - 2001-10-26T19:32:52Z
                - 2001-10-26T19:32:52.126789
                - 2001-10-26T21:32:52.126
                - -2001-10-26T21:32:52.126Z
            """
            date = format_date(self.year, self.month, self.day)
            time = format_time(self.hour, self.minute, self.second, self.fractional_second)
            return f"{date}T{time}{format_offset(self.offset)}"

        def __repr__(self) -> str:
            """Return the instance string representation."""
            args = tuple(self)
            if args[-1] is None:
                args = args[:-1]

                if args[-1] == 0:
                    args = args[:-1]

            return f"{self.__class__.__qualname__}({', '.join(map(str, args))})"

        def __eq__(self, other: Any) -> bool:
            """Return self == other."""
            return _cmp(self, other, operator.eq)

        def __ne__(self, other: Any) -> bool:
            """Return self != other."""
            return _cmp(self, other, operator.ne)

        def __lt__(self, other: Any) -> bool:
            """Return self < other."""
            return _cmp(self, other, operator.lt)

        def __le__(self, other: Any) -> bool:
            """Return self <= other."""
            return _cmp(self, other, operator.le)

        def __gt__(self, other: Any) -> bool:
            """Return self > other."""
            return _cmp(self, other, operator.gt)

        def __ge__(self, other: Any) -> bool:
            """Return self >= other."""
            return _cmp(self, other, operator.ge)

#### `microsecond` `property`

Calculate the instance microseconds.

#### `duration` `property`

Calculate the instance signed duration in seconds.

#### `from_string(string)` `classmethod`

Initialize from string with format `%Y-%m-%dT%H:%M:%S%z`.

Source code in `xsdata/models/datatype.py`

    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217

    @classmethod
    def from_string(cls, string: str) -> "XmlDateTime":
        """Initialize from string with format `%Y-%m-%dT%H:%M:%S%z`."""
        (
            year,
            month,
            day,
            hour,
            minute,
            second,
            fractional_second,
            offset,
        ) = parse_date_args(string, DateFormat.DATE_TIME)

        assert year is not None
        assert month is not None
        assert day is not None
        assert hour is not None
        assert minute is not None
        assert second is not None
        assert fractional_second is not None

        validate_date(year, month, day)
        validate_time(hour, minute, second, fractional_second)

        return cls(year, month, day, hour, minute, second, fractional_second, offset)

#### `from_datetime(obj)` `classmethod`

Initialize from `datetime.datetime` instance.

Source code in `xsdata/models/datatype.py`

    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231

    @classmethod
    def from_datetime(cls, obj: datetime.datetime) -> "XmlDateTime":
        """Initialize from `datetime.datetime` instance."""
        return cls(
            obj.year,
            obj.month,
            obj.day,
            obj.hour,
            obj.minute,
            obj.second,
            obj.microsecond * 1000,
            calculate_offset(obj),
        )

#### `now(tz=None)` `classmethod`

Initialize with the current datetime and the given timezone.

Source code in `xsdata/models/datatype.py`

    233
    234
    235
    236

    @classmethod
    def now(cls, tz: datetime.timezone | None = None) -> "XmlDateTime":
        """Initialize with the current datetime and the given timezone."""
        return cls.from_datetime(datetime.datetime.now(tz=tz))

#### `utcnow()` `classmethod`

Initialize with the current datetime and utc timezone.

Source code in `xsdata/models/datatype.py`

    238
    239
    240
    241

    @classmethod
    def utcnow(cls) -> "XmlDateTime":
        """Initialize with the current datetime and utc timezone."""
        return cls.from_datetime(datetime.datetime.now(datetime.timezone.utc))

#### `to_datetime()`

Return a `datetime.datetime` instance.

Source code in `xsdata/models/datatype.py`

    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254

    def to_datetime(self) -> datetime.datetime:
        """Return a `datetime.datetime` instance."""
        return datetime.datetime(
            self.year,
            self.month,
            self.day,
            self.hour,
            self.minute,
            self.second,
            self.microsecond,
            tzinfo=calculate_timezone(self.offset),
        )

#### `replace(year=None, month=None, day=None, hour=None, minute=None, second=None, fractional_second=None, offset=True)`

Return a new instance replacing the specified fields with new values.

Source code in `xsdata/models/datatype.py`

    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287

    def replace(
        self,
        year: int | None = None,
        month: int | None = None,
        day: int | None = None,
        hour: int | None = None,
        minute: int | None = None,
        second: int | None = None,
        fractional_second: int | None = None,
        offset: int | None = True,
    ) -> "XmlDateTime":
        """Return a new instance replacing the specified fields with new values."""
        if year is None:
            year = self.year
        if month is None:
            month = self.month
        if day is None:
            day = self.day
        if hour is None:
            hour = self.hour
        if minute is None:
            minute = self.minute
        if second is None:
            second = self.second
        if fractional_second is None:
            fractional_second = self.fractional_second
        if offset is True:
            offset = self.offset

        return type(self)(
            year, month, day, hour, minute, second, fractional_second, offset
        )

#### `__str__()`

Return the datetime formatted according to ISO 8601 for xml.

Examples:

- 2001-10-26T21:32:52
- 2001-10-26T21:32:52+02:00
- 2001-10-26T19:32:52Z
- 2001-10-26T19:32:52.126789
- 2001-10-26T21:32:52.126
- -2001-10-26T21:32:52.126Z

Source code in `xsdata/models/datatype.py`

    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302

    def __str__(self) -> str:
        """Return the datetime formatted according to ISO 8601 for xml.

        Examples:
            - 2001-10-26T21:32:52
            - 2001-10-26T21:32:52+02:00
            - 2001-10-26T19:32:52Z
            - 2001-10-26T19:32:52.126789
            - 2001-10-26T21:32:52.126
            - -2001-10-26T21:32:52.126Z
        """
        date = format_date(self.year, self.month, self.day)
        time = format_time(self.hour, self.minute, self.second, self.fractional_second)
        return f"{date}T{time}{format_offset(self.offset)}"

#### `__repr__()`

Return the instance string representation.

Source code in `xsdata/models/datatype.py`

    304
    305
    306
    307
    308
    309
    310
    311
    312
    313

    def __repr__(self) -> str:
        """Return the instance string representation."""
        args = tuple(self)
        if args[-1] is None:
            args = args[:-1]

            if args[-1] == 0:
                args = args[:-1]

        return f"{self.__class__.__qualname__}({', '.join(map(str, args))})"

#### `__eq__(other)`

Return self == other.

Source code in `xsdata/models/datatype.py`

    315
    316
    317

    def __eq__(self, other: Any) -> bool:
        """Return self == other."""
        return _cmp(self, other, operator.eq)

#### `__ne__(other)`

Return self != other.

Source code in `xsdata/models/datatype.py`

    319
    320
    321

    def __ne__(self, other: Any) -> bool:
        """Return self != other."""
        return _cmp(self, other, operator.ne)

#### `__lt__(other)`

Return self < other.

Source code in `xsdata/models/datatype.py`

    323
    324
    325

    def __lt__(self, other: Any) -> bool:
        """Return self < other."""
        return _cmp(self, other, operator.lt)

#### `__le__(other)`

Return self <= other.

Source code in `xsdata/models/datatype.py`

    327
    328
    329

    def __le__(self, other: Any) -> bool:
        """Return self <= other."""
        return _cmp(self, other, operator.le)

#### `__gt__(other)`

Return self > other.

Source code in `xsdata/models/datatype.py`

    331
    332
    333

    def __gt__(self, other: Any) -> bool:
        """Return self > other."""
        return _cmp(self, other, operator.gt)

#### `__ge__(other)`

Return self >= other.

Source code in `xsdata/models/datatype.py`

    335
    336
    337

    def __ge__(self, other: Any) -> bool:
        """Return self >= other."""
        return _cmp(self, other, operator.ge)

### `XmlTime`

Bases: `NamedTuple`

Concrete xs:time builtin type.

Represents iso 8601 time format `hh:mm: ss[Z|(+|-)hh:mm]` with rich comparisons and hashing.

Attributes:

Name | Type | Description
--- | --- | ---
`hour` | `int` | Unsigned integer between 0-24
`minute` | `int` | Unsigned integer between 0-59
`second` | `int` | Unsigned integer between 0-59
`fractional_second` | `int` | Unsigned integer between 0-999999999
`offset` | `int | None` | Signed integer representing timezone offset in minutes

Source code in `xsdata/models/datatype.py`

    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487

    class XmlTime(NamedTuple):
        """Concrete xs:time builtin type.

        Represents iso 8601 time format `hh:mm: ss[Z|(+|-)hh:mm]`
        with rich comparisons and hashing.

        Attributes:
            hour: Unsigned integer between 0-24
            minute: Unsigned integer between 0-59
            second: Unsigned integer between 0-59
            fractional_second: Unsigned integer between 0-999999999
            offset: Signed integer representing timezone offset in minutes
        """

        hour: int
        minute: int
        second: int
        fractional_second: int = 0
        offset: int | None = None

        @property
        def microsecond(self) -> int:
            """Calculate the instance microseconds."""
            return self.fractional_second // 1000

        @property
        def duration(self) -> float:
            """Calculate the total duration in seconds."""
            return (
                self.hour * DS_HOUR
                + self.minute * DS_MINUTE
                + self.second
                + self.fractional_second * DS_FRACTIONAL_SECOND
                + (self.offset or 0) * DS_OFFSET
            )

        def replace(
            self,
            hour: int | None = None,
            minute: int | None = None,
            second: int | None = None,
            fractional_second: int | None = None,
            offset: int | None = True,
        ) -> "XmlTime":
            """Return a new instance replacing the specified fields with new values."""
            if hour is None:
                hour = self.hour
            if minute is None:
                minute = self.minute
            if second is None:
                second = self.second
            if fractional_second is None:
                fractional_second = self.fractional_second
            if offset is True:
                offset = self.offset

            return type(self)(hour, minute, second, fractional_second, offset)

        @classmethod
        def from_string(cls, string: str) -> "XmlTime":
            """Initialize from string format `%H:%M:%S%z`."""
            (hour, minute, second, fractional_second, offset) = parse_date_args(
                string, DateFormat.TIME
            )

            assert hour is not None
            assert minute is not None
            assert second is not None
            assert fractional_second is not None

            validate_time(hour, minute, second, fractional_second)
            return cls(hour, minute, second, fractional_second, offset)

        @classmethod
        def from_time(cls, obj: datetime.time) -> "XmlTime":
            """Initialize from `datetime.time` instance."""
            return cls(
                obj.hour,
                obj.minute,
                obj.second,
                obj.microsecond * 1000,
                calculate_offset(obj),
            )

        @classmethod
        def now(cls, tz: datetime.timezone | None = None) -> "XmlTime":
            """Initialize with the current time and the given timezone."""
            return cls.from_time(datetime.datetime.now(tz=tz).time())

        @classmethod
        def utcnow(cls) -> "XmlTime":
            """Initialize with the current time and utc timezone."""
            return cls.from_time(datetime.datetime.now(datetime.timezone.utc).time())

        def to_time(self) -> datetime.time:
            """Convert to a `datetime.time` instance."""
            return datetime.time(
                self.hour,
                self.minute,
                self.second,
                self.microsecond,
                tzinfo=calculate_timezone(self.offset),
            )

        def __str__(self) -> str:
            """Return the time formatted according to ISO 8601 for xml.

            Examples:
                - 21:32:52
                - 21:32:52+02:00,
                - 19:32:52Z
                - 21:32:52.126789
                - 21:32:52.126Z
            """
            time = format_time(self.hour, self.minute, self.second, self.fractional_second)
            return f"{time}{format_offset(self.offset)}"

        def __repr__(self) -> str:
            """Return the instance string representation."""
            args = list(self)
            if args[-1] is None:
                del args[-1]

            return f"{self.__class__.__qualname__}({', '.join(map(str, args))})"

        def __eq__(self, other: Any) -> bool:
            """Return self == other."""
            return _cmp(self, other, operator.eq)

        def __ne__(self, other: Any) -> bool:
            """Return self != other."""
            return _cmp(self, other, operator.ne)

        def __lt__(self, other: Any) -> bool:
            """Return self < other."""
            return _cmp(self, other, operator.lt)

        def __le__(self, other: Any) -> bool:
            """Return self <= other."""
            return _cmp(self, other, operator.le)

        def __gt__(self, other: Any) -> bool:
            """Return self > other."""
            return _cmp(self, other, operator.gt)

        def __ge__(self, other: Any) -> bool:
            """Return self >= other."""
            return _cmp(self, other, operator.ge)

#### `microsecond` `property`

Calculate the instance microseconds.

#### `duration` `property`

Calculate the total duration in seconds.

#### `replace(hour=None, minute=None, second=None, fractional_second=None, offset=True)`

Return a new instance replacing the specified fields with new values.

Source code in `xsdata/models/datatype.py`

    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396

    def replace(
        self,
        hour: int | None = None,
        minute: int | None = None,
        second: int | None = None,
        fractional_second: int | None = None,
        offset: int | None = True,
    ) -> "XmlTime":
        """Return a new instance replacing the specified fields with new values."""
        if hour is None:
            hour = self.hour
        if minute is None:
            minute = self.minute
        if second is None:
            second = self.second
        if fractional_second is None:
            fractional_second = self.fractional_second
        if offset is True:
            offset = self.offset

        return type(self)(hour, minute, second, fractional_second, offset)

#### `from_string(string)` `classmethod`

Initialize from string format `%H:%M:%S%z`.

Source code in `xsdata/models/datatype.py`

    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411

    @classmethod
    def from_string(cls, string: str) -> "XmlTime":
        """Initialize from string format `%H:%M:%S%z`."""
        (hour, minute, second, fractional_second, offset) = parse_date_args(
            string, DateFormat.TIME
        )

        assert hour is not None
        assert minute is not None
        assert second is not None
        assert fractional_second is not None

        validate_time(hour, minute, second, fractional_second)
        return cls(hour, minute, second, fractional_second, offset)

#### `from_time(obj)` `classmethod`

Initialize from `datetime.time` instance.

Source code in `xsdata/models/datatype.py`

    413
    414
    415
    416
    417
    418
    419
    420
    421
    422

    @classmethod
    def from_time(cls, obj: datetime.time) -> "XmlTime":
        """Initialize from `datetime.time` instance."""
        return cls(
            obj.hour,
            obj.minute,
            obj.second,
            obj.microsecond * 1000,
            calculate_offset(obj),
        )

#### `now(tz=None)` `classmethod`

Initialize with the current time and the given timezone.

Source code in `xsdata/models/datatype.py`

    424
    425
    426
    427

    @classmethod
    def now(cls, tz: datetime.timezone | None = None) -> "XmlTime":
        """Initialize with the current time and the given timezone."""
        return cls.from_time(datetime.datetime.now(tz=tz).time())

#### `utcnow()` `classmethod`

Initialize with the current time and utc timezone.

Source code in `xsdata/models/datatype.py`

    429
    430
    431
    432

    @classmethod
    def utcnow(cls) -> "XmlTime":
        """Initialize with the current time and utc timezone."""
        return cls.from_time(datetime.datetime.now(datetime.timezone.utc).time())

#### `to_time()`

Convert to a `datetime.time` instance.

Source code in `xsdata/models/datatype.py`

    434
    435
    436
    437
    438
    439
    440
    441
    442

    def to_time(self) -> datetime.time:
        """Convert to a `datetime.time` instance."""
        return datetime.time(
            self.hour,
            self.minute,
            self.second,
            self.microsecond,
            tzinfo=calculate_timezone(self.offset),
        )

#### `__str__()`

Return the time formatted according to ISO 8601 for xml.

Examples:

- 21:32:52
- 21:32:52+02:00,
- 19:32:52Z
- 21:32:52.126789
- 21:32:52.126Z

Source code in `xsdata/models/datatype.py`

    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455

    def __str__(self) -> str:
        """Return the time formatted according to ISO 8601 for xml.

        Examples:
            - 21:32:52
            - 21:32:52+02:00,
            - 19:32:52Z
            - 21:32:52.126789
            - 21:32:52.126Z
        """
        time = format_time(self.hour, self.minute, self.second, self.fractional_second)
        return f"{time}{format_offset(self.offset)}"

#### `__repr__()`

Return the instance string representation.

Source code in `xsdata/models/datatype.py`

    457
    458
    459
    460
    461
    462
    463

    def __repr__(self) -> str:
        """Return the instance string representation."""
        args = list(self)
        if args[-1] is None:
            del args[-1]

        return f"{self.__class__.__qualname__}({', '.join(map(str, args))})"

#### `__eq__(other)`

Return self == other.

Source code in `xsdata/models/datatype.py`

    465
    466
    467

    def __eq__(self, other: Any) -> bool:
        """Return self == other."""
        return _cmp(self, other, operator.eq)

#### `__ne__(other)`

Return self != other.

Source code in `xsdata/models/datatype.py`

    469
    470
    471

    def __ne__(self, other: Any) -> bool:
        """Return self != other."""
        return _cmp(self, other, operator.ne)

#### `__lt__(other)`

Return self < other.

Source code in `xsdata/models/datatype.py`

    473
    474
    475

    def __lt__(self, other: Any) -> bool:
        """Return self < other."""
        return _cmp(self, other, operator.lt)

#### `__le__(other)`

Return self <= other.

Source code in `xsdata/models/datatype.py`

    477
    478
    479

    def __le__(self, other: Any) -> bool:
        """Return self <= other."""
        return _cmp(self, other, operator.le)

#### `__gt__(other)`

Return self > other.

Source code in `xsdata/models/datatype.py`

    481
    482
    483

    def __gt__(self, other: Any) -> bool:
        """Return self > other."""
        return _cmp(self, other, operator.gt)

#### `__ge__(other)`

Return self >= other.

Source code in `xsdata/models/datatype.py`

    485
    486
    487

    def __ge__(self, other: Any) -> bool:
        """Return self >= other."""
        return _cmp(self, other, operator.ge)

### `TimeInterval`

Bases: `NamedTuple`

Time interval model representation.

Source code in `xsdata/models/datatype.py`

    500
    501
    502
    503
    504
    505
    506
    507
    508
    509

    class TimeInterval(NamedTuple):
        """Time interval model representation."""

        negative: bool
        years: int | None
        months: int | None
        days: int | None
        hours: int | None
        minutes: int | None
        seconds: float | None

### `XmlDuration`

Bases: `UserString`

Concrete xs:duration builtin type.

Represents iso 8601 duration format PnYnMnDTnHnMnS with rich comparisons and hashing.

Format PnYnMnDTnHnMnS

- P: literal value that starts the expression
- nY: the number of years followed by a literal Y
- nM: the number of months followed by a literal M
- nD: the number of days followed by a literal D
- T: literal value that separates date and time parts
- nH: the number of hours followed by a literal H
- nM: the number of minutes followed by a literal M
- nS: the number of seconds followed by a literal S

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`value` | `str` | String representation of a xs:duration, eg P2Y6M5DT12H | required

Source code in `xsdata/models/datatype.py`

    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601

    class XmlDuration(UserString):
        """Concrete xs:duration builtin type.

        Represents iso 8601 duration format PnYnMnDTnHnMnS
        with rich comparisons and hashing.

        Format PnYnMnDTnHnMnS:
            - **P**: literal value that starts the expression
            - **nY**: the number of years followed by a literal Y
            - **nM**: the number of months followed by a literal M
            - **nD**: the number of days followed by a literal D
            - **T**: literal value that separates date and time parts
            - **nH**: the number of hours followed by a literal H
            - **nM**: the number of minutes followed by a literal M
            - **nS**: the number of seconds followed by a literal S

        Args:
            value: String representation of a xs:duration, eg **P2Y6M5DT12H**
        """

        def __init__(self, value: str) -> None:
            """Initialize with the given string."""
            super().__init__(value)
            self._interval = self._parse_interval(value)

        @property
        def years(self) -> int | None:
            """Number of years in the interval."""
            return self._interval.years

        @property
        def months(self) -> int | None:
            """Number of months in the interval."""
            return self._interval.months

        @property
        def days(self) -> int | None:
            """Number of days in the interval."""
            return self._interval.days

        @property
        def hours(self) -> int | None:
            """Number of hours in the interval."""
            return self._interval.hours

        @property
        def minutes(self) -> int | None:
            """Number of minutes in the interval."""
            return self._interval.minutes

        @property
        def seconds(self) -> float | None:
            """Number of seconds in the interval."""
            return self._interval.seconds

        @property
        def negative(self) -> bool:
            """Negative flag of the interval."""
            return self._interval.negative

        @classmethod
        def _parse_interval(cls, value: str) -> TimeInterval:
            if not isinstance(value, str):
                raise ValueError("Value must be string")

            if len(value) < 3 or value.endswith("T"):
                raise ValueError(f"Invalid format '{value}'")

            match = xml_duration_re.match(value)
            if not match:
                raise ValueError(f"Invalid format '{value}'")

            sign, years, months, days, hours, minutes, seconds, _ = match.groups()
            return TimeInterval(
                negative=sign == "-",
                years=int(years) if years else None,
                months=int(months) if months else None,
                days=int(days) if days else None,
                hours=int(hours) if hours else None,
                minutes=int(minutes) if minutes else None,
                seconds=float(seconds) if seconds else None,
            )

        def asdict(self) -> dict:
            """Return instance as a dict."""
            return self._interval._asdict()

        def __repr__(self) -> str:
            """Return the instance string representation."""
            return f'{self.__class__.__qualname__}("{self.data}")'

#### `years` `property`

Number of years in the interval.

#### `months` `property`

Number of months in the interval.

#### `days` `property`

Number of days in the interval.

#### `hours` `property`

Number of hours in the interval.

#### `minutes` `property`

Number of minutes in the interval.

#### `seconds` `property`

Number of seconds in the interval.

#### `negative` `property`

Negative flag of the interval.

#### `__init__(value)`

Initialize with the given string.

Source code in `xsdata/models/datatype.py`

    532
    533
    534
    535

    def __init__(self, value: str) -> None:
        """Initialize with the given string."""
        super().__init__(value)
        self._interval = self._parse_interval(value)

#### `asdict()`

Return instance as a dict.

Source code in `xsdata/models/datatype.py`

    595
    596
    597

    def asdict(self) -> dict:
        """Return instance as a dict."""
        return self._interval._asdict()

#### `__repr__()`

Return the instance string representation.

Source code in `xsdata/models/datatype.py`

    599
    600
    601

    def __repr__(self) -> str:
        """Return the instance string representation."""
        return f'{self.__class__.__qualname__}("{self.data}")'

### `TimePeriod`

Bases: `NamedTuple`

Time period model representation.

Source code in `xsdata/models/datatype.py`

    604
    605
    606
    607
    608
    609
    610

    class TimePeriod(NamedTuple):
        """Time period model representation."""

        year: int | None
        month: int | None
        day: int | None
        offset: int | None

### `XmlPeriod`

Bases: `UserString`

Concrete xs:gYear/Month/Day builtin type.

Represents iso 8601 period formats with rich comparisons and hashing.

Formats

- xs:gDay: ---%d%z
- xs:gMonth: --%m%z
- xs:gYear: %Y%z
- xs:gMonthDay: --%m-%d%z
- xs:gYearMonth: %Y-%m%z

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`value` | `str` | String representation of a xs:period, eg --11-01Z | required

Source code in `xsdata/models/datatype.py`

    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696

    class XmlPeriod(UserString):
        """Concrete xs:gYear/Month/Day builtin type.

        Represents iso 8601 period formats with rich comparisons and hashing.

        Formats:
            - xs:gDay: **---%d%z**
            - xs:gMonth: **--%m%z**
            - xs:gYear: **%Y%z**
            - xs:gMonthDay: **--%m-%d%z**
            - xs:gYearMonth: **%Y-%m%z**

        Args:
            value: String representation of a xs:period, eg **--11-01Z**
        """

        def __init__(self, value: str) -> None:
            """Initialize a xs:period."""
            value = value.strip()
            super().__init__(value)
            self._period = self._parse_period(value)

        @property
        def year(self) -> int | None:
            """Period year."""
            return self._period.year

        @property
        def month(self) -> int | None:
            """Period month."""
            return self._period.month

        @property
        def day(self) -> int | None:
            """Period day."""
            return self._period.day

        @property
        def offset(self) -> int | None:
            """Period timezone offset in minutes."""
            return self._period.offset

        @classmethod
        def _parse_period(cls, value: str) -> TimePeriod:
            year = month = day = offset = None
            if value.startswith("---"):
                day, offset = parse_date_args(value, DateFormat.G_DAY)
            elif value.startswith("--"):
                # Bogus format --MM--, --05---05:00
                if value[4:6] == "--":
                    value = value[:4] + value[6:]

                if len(value) in (4, 5, 10):  # fixed lengths with/out timezone
                    month, offset = parse_date_args(value, DateFormat.G_MONTH)
                else:
                    month, day, offset = parse_date_args(value, DateFormat.G_MONTH_DAY)
            else:
                end = len(value)
                if value.find(":") > -1:  # offset
                    end -= 6

                if value[:end].rfind("-") > 3:  # Minimum position for month sep
                    year, month, offset = parse_date_args(value, DateFormat.G_YEAR_MONTH)
                else:
                    year, offset = parse_date_args(value, DateFormat.G_YEAR)

            validate_date(0, month or 1, day or 1)

            return TimePeriod(year=year, month=month, day=day, offset=offset)

        def as_dict(self) -> dict:
            """Return date units as dict."""
            return self._period._asdict()

        def __repr__(self) -> str:
            """Return the instance string representation."""
            return f'{self.__class__.__qualname__}("{self.data}")'

        def __eq__(self, other: Any) -> bool:
            """Return self == other."""
            if isinstance(other, XmlPeriod):
                return self._period == other._period

            return NotImplemented

#### `year` `property`

Period year.

#### `month` `property`

Period month.

#### `day` `property`

Period day.

#### `offset` `property`

Period timezone offset in minutes.

#### `__init__(value)`

Initialize a xs:period.

Source code in `xsdata/models/datatype.py`

    629
    630
    631
    632
    633

    def __init__(self, value: str) -> None:
        """Initialize a xs:period."""
        value = value.strip()
        super().__init__(value)
        self._period = self._parse_period(value)

#### `as_dict()`

Return date units as dict.

Source code in `xsdata/models/datatype.py`

    683
    684
    685

    def as_dict(self) -> dict:
        """Return date units as dict."""
        return self._period._asdict()

#### `__repr__()`

Return the instance string representation.

Source code in `xsdata/models/datatype.py`

    687
    688
    689

    def __repr__(self) -> str:
        """Return the instance string representation."""
        return f'{self.__class__.__qualname__}("{self.data}")'

#### `__eq__(other)`

Return self == other.

Source code in `xsdata/models/datatype.py`

    691
    692
    693
    694
    695
    696

    def __eq__(self, other: Any) -> bool:
        """Return self == other."""
        if isinstance(other, XmlPeriod):
            return self._period == other._period

        return NotImplemented

### `XmlHexBinary`

Bases: `bytes`

Subclass bytes to infer base16 format.

This type can be used with xs:anyType fields that don't have a format property to specify the target output format.

Source code in `xsdata/models/datatype.py`

    699
    700
    701
    702
    703
    704

    class XmlHexBinary(bytes):
        """Subclass bytes to infer base16 format.

        This type can be used with xs:anyType fields that don't have a
        format property to specify the target output format.
        """

### `XmlBase64Binary`

Bases: `bytes`

Subclass bytes to infer base64 format.

This type can be used with xs:anyType fields that don't have a format property to specify the target output format.

Source code in `xsdata/models/datatype.py`

    707
    708
    709
    710
    711
    712

    class XmlBase64Binary(bytes):
        """Subclass bytes to infer base64 format.

        This type can be used with xs:anyType fields that don't have a
        format property to specify the target output format.
        """