简体   繁体   English

如何使用Python格式化分钟/秒?

[英]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 00分钟1.0010秒

Meaning: as expected, 0 minutes are showing up as "00". 含义:如预期的那样,0分钟显示为“ 00”。 But 1 seconds shows up as 1.xxxx - instead of 01.xxxx 但是1秒显示为1.xxxx-而不是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: 对于4个小数加点,再加上2个整数部分,您需要7个字符:

>>> 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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