from datetime import datetime


def to_datetime(t):
    """Convert 6-part time tuple into datetime object.
    """
    # extract values
    year, mon, day, h, m, s = t

    # assume the values are valid
    try:
        return datetime(year, mon, day, h, m, s)
    except ValueError:
        pass

    # sanitize invalid values
    mday = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    mon = max(1, min(mon, 12))
    day = max(1, min(day, mday[mon]))
    h = min(h, 23)
    m = min(m, 59)
    s = min(s, 59)
    return datetime(year, mon, day, h, m, s)