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 >= 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.