简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM