import re


def _regexify_subfmts(subfmts):
    """
    Iterate through each of the sub-formats and try substituting simple
    regular expressions for the strptime codes for year, month, day-of-month,
    hour, minute, second.  If no % characters remain then turn the final string
    into a compiled regex.  This assumes time formats do not have a % in them.

    This is done both to speed up parsing of strings and to allow mixed formats
    where strptime does not quite work well enough.
    """
    new_subfmts = []
    for subfmt_tuple in subfmts:
        subfmt_in = subfmt_tuple[1]
        for strptime_code, regex in (('%Y', r'(?P<year>\d\d\d\d)'),
                                     ('%m', r'(?P<mon>\d{1,2})'),
                                     ('%d', r'(?P<mday>\d{1,2})'),
                                     ('%H', r'(?P<hour>\d{1,2})'),
                                     ('%M', r'(?P<min>\d{1,2})'),
                                     ('%S', r'(?P<sec>\d{1,2})')):
            subfmt_in = subfmt_in.replace(strptime_code, regex)

        if '%' not in subfmt_in:
            subfmt_tuple = (subfmt_tuple[0],
                            re.compile(subfmt_in + '$'),
                            subfmt_tuple[2])
        new_subfmts.append(subfmt_tuple)

    return tuple(new_subfmts)