from datetime import datetime


def to_datetime(x):
    """Fast datetime object creation from a date string.

    Permissible string formats:

        For example '2020-12-13T13:27:15.320000Z' with:

            - optional milliseconds and microseconds with
              arbitrary precision (1 to 6 digits)
            - with optional trailing letter 'Z'

        Examples of valid formats:

            - `2020-12-13T13:27:15.320000`
            - `2020-12-13T13:27:15.32Z`
            - `2020-12-13T13:27:15`

    Args:
        x (str or datetime)
    Returns:
        datetime.datetime
    """
    if isinstance(x, str):
        date, time = x.strip('Z').split('T')
        year, month, day = date.split('-')
        hours, minutes, seconds = time.split(':')
        if '.' in seconds:
            seconds, msus = seconds.split('.')
            if len(msus) < 6:
                msus = msus+'0'*(6-len(msus))
            elif len(msus) > 6:
                msus = msus[0:6]
        else:
            msus = 0

        return datetime(int(year), int(month), int(day), int(hours),
                        int(minutes), int(seconds), int(msus))
    elif isinstance(x, datetime):
        return x