Represents a BSON UTC datetime.
| 36 | |
| 37 | |
| 38 | class DatetimeMS: |
| 39 | """Represents a BSON UTC datetime.""" |
| 40 | |
| 41 | __slots__ = ("_value",) |
| 42 | |
| 43 | def __init__(self, value: Union[int, datetime.datetime]): |
| 44 | """Represents a BSON UTC datetime. |
| 45 | |
| 46 | BSON UTC datetimes are defined as an int64 of milliseconds since the |
| 47 | Unix epoch. The principal use of DatetimeMS is to represent |
| 48 | datetimes outside the range of the Python builtin |
| 49 | :class:`~datetime.datetime` class when |
| 50 | encoding/decoding BSON. |
| 51 | |
| 52 | To decode UTC datetimes as a ``DatetimeMS``, `datetime_conversion` in |
| 53 | :class:`~bson.codec_options.CodecOptions` must be set to 'datetime_ms' or |
| 54 | 'datetime_auto'. See `handling out of range datetimes <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/dates-and-times/#handling-out-of-range-datetimes>`_ for |
| 55 | details. |
| 56 | |
| 57 | :param value: An instance of :class:`datetime.datetime` to be |
| 58 | represented as milliseconds since the Unix epoch, or int of |
| 59 | milliseconds since the Unix epoch. |
| 60 | """ |
| 61 | if isinstance(value, int): |
| 62 | if not (-(2**63) <= value <= 2**63 - 1): |
| 63 | raise OverflowError("Must be a 64-bit integer of milliseconds") |
| 64 | self._value = value |
| 65 | elif isinstance(value, datetime.datetime): |
| 66 | self._value = _datetime_to_millis(value) |
| 67 | else: |
| 68 | raise TypeError(f"{type(value)} is not a valid type for DatetimeMS") |
| 69 | |
| 70 | def __hash__(self) -> int: |
| 71 | return hash(self._value) |
| 72 | |
| 73 | def __repr__(self) -> str: |
| 74 | return type(self).__name__ + "(" + str(self._value) + ")" |
| 75 | |
| 76 | def __lt__(self, other: Union[DatetimeMS, int]) -> bool: |
| 77 | return self._value < other |
| 78 | |
| 79 | def __le__(self, other: Union[DatetimeMS, int]) -> bool: |
| 80 | return self._value <= other |
| 81 | |
| 82 | def __eq__(self, other: Any) -> bool: |
| 83 | if isinstance(other, DatetimeMS): |
| 84 | return self._value == other._value |
| 85 | return False |
| 86 | |
| 87 | def __ne__(self, other: Any) -> bool: |
| 88 | if isinstance(other, DatetimeMS): |
| 89 | return self._value != other._value |
| 90 | return True |
| 91 | |
| 92 | def __gt__(self, other: Union[DatetimeMS, int]) -> bool: |
| 93 | return self._value > other |
| 94 | |
| 95 | def __ge__(self, other: Union[DatetimeMS, int]) -> bool: |
no outgoing calls