0
votes

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?

2
use zfill for this purpose or use datetimeEpsi95
So it returned xxx/2021/05/02Sujay
Perhaps using datetime is more convenient docs.python.org/3/library/datetime.htmlDenis Jelovina

2 Answers

3
votes

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}'
0
votes

You could cast to a datetime format, then cast to a string format:

from datetime import datetime

def construct_path(year, month, day):
    dt = datetime(year=year, month=month, day=day)
    dt_as_path = dt.strftime('xxx/%Y/%m/%d')
    return dt_as_path