0
today = datetime.datetime.now()
day_before_date1 = datetime.date.today()-datetime.timedelta(days=2)
day_before_date = day_before_date1.strftime("%d")
print(day_before_date)  # 01 (is the output)

I have to use arg parser in python to take input for day. If I don't give any input it defaults to presentdate-2, which is 01.

parser.add_argument('number',type=int, help="Number represents date" , nargs='?' , default=day_before_date , const="num")

I have set default=int(day_before_date) but it still registers the input as 1 and not 01 when I print(args.number) I need 01 when i print(args.number).

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Yash
  • 11
  • 7

2 Answers2

1

You can use the str.rjust method, this will guarantee that you will only ever have 2 characters so if it is 11 it will output '11' but if it is 3 it will output '03'

>>> a = 1
>>> str(a).rjust(2,"0")
"01"

another method is to use inline formating with f-strings.

>>> a = 1
>>> b = f"{a:02d}"
>>> b
"01"

Or you can use conditional statement (not recommended).

>>> a = 1
>>> b = '0' + str(a) if len(str(a)) == 1 else str(a)
>>> b
'01'
Alexander
  • 16,091
  • 5
  • 13
  • 29
0

You have two options. The first is to change what type your argument is in argparser:

parser.add_argument('number',type=str, help="Number represents date" , nargs='?' , default="01", const="num")
...
day_number_arg = int(args.number)
... # use `day_number_arg` wherever you would have used `args.number`
print(args.number)  # will print '01' if the default is used.

Here you take in a string and convert it to a number. You can print out the original argument as the string passed in, or the default.

Elsewise you can take your calculated value and use a format string:

day_number = 1
f"{day_number:02d}"

This says 'print two digits of day_number'. In this manner you can format the output, meaning you can use whatever your final value is. In general this would be the recommend method.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
  • ``` parser.add_argument('number',type=str, help="Number represents date" , nargs='?' , default="01", const="num") ... day_number_arg = int(args.number) ... # use `day_number_arg` wherever you would have used `args.number` print(args.number) ``` This gives 1 not ```01``` – Yash Jun 03 '22 at 14:29