MCPcopy Index your code
hub / github.com/mongodb/mongo-python-driver / _encode_datetime

Function _encode_datetime

bson/json_util.py:908–928  ·  view source on GitHub ↗
(obj: datetime.datetime, json_options: JSONOptions)

Source from the content-addressed store, hash-verified

906
907
908def _encode_datetime(obj: datetime.datetime, json_options: JSONOptions) -> dict: # type: ignore[type-arg]
909 if json_options.datetime_representation == DatetimeRepresentation.ISO8601:
910 if not obj.tzinfo:
911 obj = obj.replace(tzinfo=utc)
912 assert obj.tzinfo is not None
913 if obj >= EPOCH_AWARE:
914 off = obj.tzinfo.utcoffset(obj)
915 if (off.days, off.seconds, off.microseconds) == (0, 0, 0): # type: ignore
916 tz_string = "Z"
917 else:
918 tz_string = obj.strftime("%z")
919 millis = int(obj.microsecond / 1000)
920 fracsecs = ".%03d" % (millis,) if millis else ""
921 return {
922 "$date": "{}{}{}".format(obj.strftime("%Y-%m-%dT%H:%M:%S"), fracsecs, tz_string)
923 }
924
925 millis = _datetime_to_millis(obj)
926 if json_options.datetime_representation == DatetimeRepresentation.LEGACY:
927 return {"$date": millis}
928 return {"$date": {"$numberLong": str(millis)}}
929
930
931def _encode_bytes(obj: bytes, json_options: JSONOptions) -> dict: # type: ignore[type-arg]

Callers 1

_encode_datetimemsFunction · 0.70

Calls 2

_datetime_to_millisFunction · 0.90
utcoffsetMethod · 0.45

Tested by

no test coverage detected