GhostCat
GhostCat

Reputation: 140613

How to format minutes/seconds with Python?

I want to take the time that some operations need; so I wrote:

def get_formatted_delta(start_time):
    seconds = ( datetime.datetime.now() - start_time ).total_seconds()
    m, s = divmod(seconds, 60)
    min = '{:02.0f}'.format(m)
    sec = '{:02.4f}'.format(s)
    return '{} minute(s) {} seconds'.format(min, sec)

but when I run that; I get printouts like:

00 minute(s) 1.0010 seconds

Meaning: as expected, 0 minutes are showing up as "00". But 1 seconds shows up as 1.xxxx - instead of 01.xxxx

So, what is wrong with my format specification?

Upvotes: 2

Views: 967

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124548

The field width applies to the whole field including the decimals and the decimal point. For 4 decimals plus the point, plus 2 places for the integer portion, you need 7 characters:

>>> format(1.001, '07.4f')
'01.0010'

You don't need to format those floats separately, you can do all formatting and interpolation in one step:

def get_formatted_delta(start_time):
    seconds = ( datetime.datetime.now() - start_time ).total_seconds()
    m, s = divmod(seconds, 60)
    return '{:02.0f} minute(s) {:07.4f} seconds'.format(m, s)

Upvotes: 6

Related Questions