Home > Software design >  How to avoid using duplicate string literals in python
How to avoid using duplicate string literals in python

Time:02-04

I am trying to format the first input parameter 'str' to the function which is a date in string format coming from MySQL database and here i am trying to convert it to the format "%Y-%m-%d" at 4 different places which is kind of redundant at many places. Can someone please help me in telling how can i get rid of duplicating this literal everywhere? Here is my code -

def date_format(str, table, dc):
    try:
        print('it is running')
        date = ''
        str_len = len(str)
        rootLogger.info(f'the length of {str} is {str_len}')
        if str_len == 10:
            date = str
        if str_len == 19:
            date = datetime.strftime(datetime.strptime(str, "%Y-%m-%d %H:%M:%S"), "%Y-%m-%d")
        elif str_len == 20:
            date = datetime.strftime(datetime.strptime(str, "%Y-%m-%dT%H:%M:%SZ"), "%Y-%m-%d")
        elif str_len == 26:
            date = datetime.strftime(datetime.strptime(str, "%Y-%m-%d %H:%M:%S.%f"), "%Y-%m-%d")
        rootLogger.info(f'the date is {date}')

        return date

    except Exception as e:
        print(e)
        raise

if __name__=="__main__":
    curr_dt = datetime.now().strftime("%Y-%m-%d")
    date_format('2011-01-13 06:12:41','test',8134)

CodePudding user response:

Add additiinal function

def get_date(date_str: str, format_: str):
    return datetime.strftime(datetime.strptime(date_str, format_), "%Y-%m-%d")

And use it as follows:

date = get_date(str, "%Y-%m-%d %H:%M:%S")

P.S. Avoid using built-in names as variable identificators

  •  Tags:  
  • Related