Search code examples
pythonif-statementf-string

What's the simplest way to add '0' for month and day which are integers?


I have inputs month and day which are both int type, I want to pass them to a function to construct a path, and if month or day are numbers below 10, we add a 0 in front of the number:

def construct_path(year, month, day):
    if month >= 10 or day >= 10:
       path = f"xxx/{year}/{month}/{day}"
    elif month < 10 and day >= 10:
       path = f"xxx/{year}/0{month}/{day}"
    elif month >=10 and day <10:
       path = f"xxx/{year}/{month}/0{day}"
    else:
       path = f"xxx/{year}/0{month}/0{day}"
    return path

So construct_path(2021, 5, 2) should return xxx/2021/05/02.

The code works but looks complicated, is there a better way to achieve this?


Solution

  • You can use :02d with formatting to allocate two spaces for a digit, and fill it up with 0 if the space remains empty.

    def construct_path(year, month, day):
        return f'xxx/{year}/{month:02d}/{day:02d}'