def _format_datetime(dttm):
if dttm.tzinfo is None or dttm.tzinfo.utcoffset(dttm) is None:<EOL><INDENT>zoned = pytz.utc.localize(dttm)<EOL><DEDENT>else:<EOL><INDENT>zoned = dttm.astimezone(pytz.utc)<EOL><DEDENT>ts = zoned.strftime("<STR_LIT>")<EOL>ms = zoned.strftime("<STR_LIT>")<EOL>precision = getattr(dttm, "<STR_LIT>", None)<EOL>if precision == "<STR_LIT>":<EOL><INDENT>pass  <EOL><DEDENT>elif precision == "<STR_LIT>":<EOL><INDENT>ts = ts + "<STR_LIT:.>" + ms[:<NUM_LIT:3>]<EOL><DEDENT>elif zoned.microsecond > <NUM_LIT:0>:<EOL><INDENT>ts = ts + "<STR_LIT:.>" + ms.rstrip("<STR_LIT:0>")<EOL><DEDENT>return ts + "<STR_LIT>"<EOL>
Convert a datetime object into a valid STIX timestamp string.

    1. Convert to timezone-aware
    2. Convert to UTC
    3. Format in ISO format
    4. Ensure correct precision
       a. Add subsecond value if non-zero and precision not defined
    5. Add "Z"