def strftime_with_precision(tick, format, sub_secs_precision=2):
    """
    Returns a formatted string for a datetime (tick).
    :param tick: The datetime for this tick
    :param format: The formatting string
    :param sub_secs_precision: Number of digits to used for sub-seconds.
        If None, will choose it "smartly/dynamically"
    :return: Formatted string
    """
    t = tick.strftime(format)
    is_us = '%f' in format
    if is_us:
        if sub_secs_precision is None:
            while t[-1] == '0':
                t = t[:-1]
            while not t[-1].isdigit():
                t = t[:-1]
            return t
        else:
            if sub_secs_precision < 0:
                sub_secs_precision = 0
            elif sub_secs_precision > 6:
                sub_secs_precision = 6

            DFLT_PRECISION = 6
            digits_to_skip = DFLT_PRECISION - sub_secs_precision
            if digits_to_skip == 0:
                return t
            else:
                t = t[:-digits_to_skip]
                while not t[-1].isdigit():
                    t = t[:-1]
                return t
    else:
        return t