0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
wawawa
  • 2,835
  • 6
  • 44
  • 105

2 Answers2

4

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}'
martineau
  • 119,623
  • 25
  • 170
  • 301
Jelle Westra
  • 526
  • 3
  • 8
  • A quick follow-up question, what is the inputs `year`, `month` and `day` are strings and I don't want the s3 path determined by the format of the input, for example, `year` is a string `000001999`, `month` is string `00004` and day is an integer `20`, I still want the path to be `xxx/1999/04/20`, is there a way to do this? – wawawa Jul 08 '21 at 14:00
  • 1
    @Cecilia So in the line below, `day` and `month` get converted to `str` if they are a `int` in the `:02d` fashion. However, if `day` or `month` is not `int`, just take the last two characters of the string. `day, month = ['{0:02d}'.format(e if type(e) == int else int(e[-2:])) for e in [day, month]]` Same for year, assuming only years with 4 digits. `year = str(year) if type(year) == int else year[-4:]` Now you can return `f'xxx/{year}/{month}/{day}'` – Jelle Westra Jul 08 '21 at 14:28
0

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
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
  • Doesn't seem like the simplest way since it requires first creating a `datatime` object in order to be able to utilize its `strftime()` method. – martineau Jul 07 '21 at 18:05
  • A 2 liner using standard python modules is pretty simple in my opinion. Curious to see what other responses are provided @martineau – Yaakov Bressler Jul 07 '21 at 19:04
  • 1
    @Jelle Westra's answer is one line including the `return` and doesn't require importing any modules whatsoever — hard to imagine anything simpler than that… – martineau Jul 07 '21 at 19:13
  • Agreed. That is a very simple solution! – Yaakov Bressler Jul 07 '21 at 19:26