从Python 3.6开始,可以使用格式化的字符串文字或f-strings 完成Python中的格式化:
hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
或str.format
以2.7开头的函数:
"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")
或甚至更旧版本的Python的字符串格式%
运算符,但请参阅文档中的注释:
"%02d:%02d:%02d" % (hours, minutes, seconds)
对于您特定的格式化时间,有time.strftime
:
import time
t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%s %p', t)