datetime_ms – Support for BSON UTC Datetime#

Tools for representing the BSON datetime type.

New in version 4.3.

class bson.datetime_ms.DatetimeMS(value: int | datetime)#

Represents a BSON UTC datetime.

BSON UTC datetimes are defined as an int64 of milliseconds since the Unix epoch. The principal use of DatetimeMS is to represent datetimes outside the range of the Python builtin datetime class when encoding/decoding BSON.

To decode UTC datetimes as a DatetimeMS, datetime_conversion in CodecOptions must be set to ‘datetime_ms’ or ‘datetime_auto’. See Handling out of range datetimes for details.

Parameters:
  • value: An instance of datetime.datetime to be represented as milliseconds since the Unix epoch, or int of milliseconds since the Unix epoch.

as_datetime(codec_options: CodecOptions[Any] = CodecOptions(document_class=dict, tz_aware=False, uuid_representation=UuidRepresentation.UNSPECIFIED, unicode_decode_error_handler='strict', tzinfo=None, type_registry=TypeRegistry(type_codecs=[], fallback_encoder=None), datetime_conversion=DatetimeConversion.DATETIME)) datetime#

Create a Python datetime from this DatetimeMS object.

Parameters:
  • codec_options: A CodecOptions instance for specifying how the resulting DatetimeMS object will be formatted using tz_aware and tz_info. Defaults to DEFAULT_CODEC_OPTIONS.