def to_datetime(t):
    """Convert 6-part time tuple into datetime object.
    """
    if t is None:
        return None

    # 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, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    if mon < 1:
        mon = 1
    if mon > 12:
        mon = 12
    if day < 1:
        day = 1
    if day > mday[mon]:
        day = mday[mon]
    if h > 23:
        h = 23
    if m > 59:
        m = 59
    if s > 59:
        s = 59
    if mon == 2 and day == 29:
        try:
            return datetime(year, mon, day, h, m, s)
        except ValueError:
            day = 28
    return datetime(year, mon, day, h, m, s)
Convert 6-part time tuple into datetime object.