Python date formatter I'd like to find the best way to format date to YYYY, YYYYMM or YYYYMMDD.
Here is what I've got so far:

# gets the position of a character in the format
def get_pos(format, letter, number):
    it_number = 0
    it_pos = 0
    for char in format:
        if char == letter:
            it_number += 1
            if it_number == number:
                return(it_pos)
        it_pos += 1
    return(-1)

# loops through all the characters forming a number
def format_loop(string, old_format, letter):
    new = ''
    pos = -2
    it = 1
    while(pos != -1):
        pos = get_pos(old_format, letter, it)
        if(pos &gt;= 0):
            new += string[pos]
        it += 1
    return(new)

# format a date
def date_format(string, old_format, new_format, delim):
    new = format_loop(string, old_format, 'Y')
    if(new_format in 'MD'):
        new += delim + format_loop(string, old_format, 'M')
    if(new_format == 'D'):
        new += delim + format_loop(string, old_format, 'D')
    return(new)


The function's intake parameters are, in order, the date string to format, its current format, the desired format in the form of 'Y', 'M' or 'D' and an optional delimiter to put in between the numbers.

I'm open for suggestions on shortening and optimising the code as well as on coding style and variables/functions naming.
For the first loop, there is a neat little function called enumerate() which allows you to iterate through an object and access both the element and the iteration number.

You can also remove various parenthesis, for the returned value and also for the while loop (although for big conditions it's handy to keep the parenthesis sometimes).

def get_pos(format, letter, number):
    it_number = 0
    # it_pos = 0 &lt;--- not needed anymore because of the
    for it_pos, char in enumerate(format): # &lt;--- enumerate
        if char == letter:
            it_number += 1
            if it_number == number:
                return it_pos
        # it_pos += 1 &lt;--- same thing here
    return -1


For the second function I would suggest to use while True and break so that you don't have to declare pos=-2 beforehand.    

def format_loop(string, old_format, letter):
    new = ''
    # pos = -2 &lt;--- replaced by a break
    it = 1
    while True:
        pos = get_pos(old_format, letter, it)
        if pos == -1:
            break
        elif pos &gt;= 0:
            new += string[pos]
        it += 1
    return new


Also, I don't know if there is an official recommendation on that, but I like to use very explicit return values for special cases, for example the string "not found" instead of -1. That makes the code more English than Python when you read if pos=="not found": break and I rather like that.