使用填充时间值打印时间戳

时间:2018-02-18 08:18:46

标签: python python-3.x

我的闹钟程序有这个代码,可以检查输入是否为HH:MM:SS格式。

def testing():
    try:
        alarm = input("> ")
        hour = int(alarm[0:2])
        minute = int(alarm[3:5])
        second = int(alarm[6:8])
        if len(alarm) == 8:
            print(("\nsets to %s:%s:%s\n" % (hour, minute, second)))
    except ValueError:
        print("format must be HH:MM:SS")
        testing()

testing()

它工作正常,除非输入是" 00:00:00",在这种情况下输出是" 0:0:0"而不是预期的输出,每个单位填充到两位数。为什么会这样?

3 个答案:

答案 0 :(得分:2)

当警报为import UIKit @IBDesignable class BorderedView: UIView { @IBInspectable var cornerRadius: CGFloat = 0 @IBInspectable var borderWidth: CGFloat = 0 @IBInspectable var borderColor: UIColor = UIColor.clear override func draw(_ rect: CGRect) { let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius) path.lineWidth = borderWidth borderColor.setStroke() let dashPattern : [CGFloat] = [10, 4] path.setLineDash(dashPattern, count: 2, phase: 0) path.stroke() } } 时,请考虑行hour = int(alarm[0:2])

"00:00:00"将为alarm[0:2]"00"为整数int("00")

0minute也是如此。当您插入secondhourminute的值时,结果为second

您可以将打印语句更改为

,将小时,分钟和秒值填充为两位数
"0:0:0"

答案 1 :(得分:0)

更改print(("\nsets to %s:%s:%s\n" % (hour, minute, second)))

print(("\nsets to %02d:%02d:%02d\n" % (hour, minute, second)))

这样可以打印2:0:0 or 0:0:0

,而不是打印02:00:00 or 00:00:00

答案 2 :(得分:0)

由于您要将值格式化为字符串,因此无需从字符串转换为整数:

hour = alarm[0:2]
minute = alarm[3:5]
second = alarm[6:8]

此外,我会使用str.format()代替%运算符,这是一种更强大的字符串格式化方法:

print("\nsets to {}:{}:{}\n".format(hour, minute, second))