Python formatting from 1 to 01
I want to be able to format the date / time input for my function.
I currently have a function that basically adds 0 to a number if it only has 1 digit.
def format_num(str(num)):
if len(num) < 2:
return "0" + num
return num
I was wondering if there is a more pythonic way to do this.
source to share
>>> ["{:02}".format(num) for num in (1,22,333)]
['01', '22', '333']
For more information about syntax, understands the method format
, see. Https://docs.python.org/2/library/string.html#formatspec .
source to share
Calling string format functions is several times slower than
>>> "%02d" % 8
'08'
>>> "%02d" % 80
'80'
Therefore, if you care about performance, try to avoid function calls.
python -m timeit "'%02d' % 8"
100000000 loops, best of 3: 0.0166 usec per loop
python -m timeit "'8'.zfill(2)"
10000000 loops, best of 3: 0.163 usec per loop
python -m timeit "'{:02}'.format(2)"
1000000 loops, best of 3: 0.385 usec per loop
In such simple and often referred to code, I would take a faster solution.
source to share
To answer your direct question -
You can format your number like this:
format(num, '02d')
Example:
nums = [1,22,333]
for num in nums:
print format(num, '02d')
Outputs:
01 22 333
However, you say that you are using date and time. You can format the datetime object directly
%d - Zero padded day %m - Zero padded month
source to share